<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */


namespace app\api\controller\android\v13;



use app\api\model\Authority;
use app\api\model\Capital;
use app\api\model\Common;
use app\api\model\House;
use app\api\model\OrderDeliveryManagerModel;
use app\api\model\OrderPaymentNodes;
use app\api\model\PollingModel;
use app\api\model\TelephoneNotification;
use redis\RedisPackage;
use shortLink\WxService;
use think\Controller;
use think\Exception;
use think\Request;
use app\api\model\OrderModel;
use app\api\validate;
use Think\Db;
use app\api\model\Approval;


class Order extends Controller {
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    
    public function _initialize() {
        $this->model    = new Authority();
        $this->us       = Authority::check(1);
        $this->newTime  = strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -5 minutes")));
        $this->endTime  = strtotime(date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s") . " -10 minutes")));
        $this->overtime = strtotime(date("Y-m-d H:i:s", strtotime(date('Y-m-d H:i:s', strtotime('+1minute')))));
    }
    
    /**
     * 发布订单
     * cate_id 二级id
     */
    public function send_need(OrderModel $orderModel, House $house) {
        
        $data           = $this->model->post(['channel_id', 'pro_id', 'province_id', 'city_id', 'county_id', 'addres', 'contacts', 'telephone', 'remarks', 'logo', 'lat', 'lng', 'channel_details', 'hardbound', 'distribution']);
        $Order_Validate = new validate\Order_Validate();
        if (!$Order_Validate->check($data)) {
            r_date($Order_Validate->getError(), 300);
        }
        if (!is_mobile($data['telephone'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        db()->startTrans();
        try {
            $city_id  = 0;
            $province = 0;
            $county   = 0;
            if ($data['province_id']) {
                $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
            }
            if ($data['city_id']) {
                $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
            }
            if ($data['county_id']) {
                $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
            }
            
            $hematopoiesis = 1;
            if ($data['channel_details'] == 102 || $data['channel_details'] == 100 || $data['channel_details'] == 96 || $hematopoiesis == 1) {
                $time = time();
            } else {
                $time = 0;
            }
            
            if ($city_id != 0) {
                $content = $orderModel->UrbanAccess($city_id);
            } else {
                throw new Exception('超出城市范围');
            }
            $business_type=1;
            if($data['pro_id']==1000){
                $business_type=2;
            }
            $attribution = db('chanel')->where('id', $data['channel_id'])->value('large_category');
            if ($attribution == 5) {
                $attribution = 4;
            } elseif ($attribution == 2) {
                $attribution = 3;
            } elseif ($attribution == 3) {
                $attribution = 3;
            }
            $hematopoiesis = 1;
//            if ($data['channel_id'] == 30) {
//                $attribution   = 3;
//                $hematopoiesis = 0;
//            }
//            $distribution = 0;
//            if ($data['channel_id'] == 27 || $data['channel_id'] == 28) {
            $distribution = isset($data['distribution']) ? $data['distribution'] : 0;//市
//            }
            if (empty($content)) {
                throw new Exception('超出城市范围');
            }
            $house        = $house->getHouse(['province' => $province, 'city' => $city_id, 'area' => $county, 'communityName' => $data['communityName'], 'address' => $data['addres'], 'latitude' => $data['lat'], 'longitude' => $data['lng']]);
            $order        = Db::connect($content)->table('order');
            $created_time = time();
            $res          = $order->insertGetId(['channel_id' => $data['channel_id'],//渠道
                'channel_details' => $data['channel_details'],//渠道
                'order_no' => order_sn(),//订单号
                'pro_id' => $data['pro_id'],//一级问题
                'province_id' => $province,//省
                'city_id' => $city_id,//市
                'wechat_id' => isset($data['wechat']) ? $data['wechat_id'] : '',//市
                'distribution' => $distribution, 'county_id' => $county,//区
                'addres' => $data['addres'],//地址
                'contacts' => $data['contacts'],//联系人
                'telephone' => $data['telephone'],//联系电话
                'remarks' => $data['remarks'],//备注
                'residential_quarters' => $data['communityName'],//备注
                'logo' => !empty($data['logo']) ? serialize(json_decode($data['logo'], true)) : '',//图片
                'street' => $data['street'], 'building' => $data['building'], 'unit' => $data['unit'], 'room' => $data['room'], 'state' => -1,//待指派
                'created_time' => $created_time,//创建时间
                'update_time' => time(),//创建时间
                'lat' => $data['lat'],//创建时间
                'lng' => $data['lng'],//创建时间
                'notcost_time' => $time,//创建时间
                'intention' => $this->us['user_id'],//创建时间
                'entry' => '店长录入-' . $this->us['username'],//创建时间
                'house_id' => $house,//创建时间
                'hardbound' => $data['hardbound'],//创建时间
                'entry_user_id' => $this->us['user_id'],//创建时间
                'entry_type' => 1, 'hematopoiesis' => $hematopoiesis, 'attributions' => $attribution,'business_type'=>$business_type]);
//            if ($data['assignor'] == 0) {
//
//            }
            (new PollingModel())->Alls($res, 0, 0, time(), time());
            $resp_pers = respPers($data['channel_details']);
//            else {
            db('biz_flw')->insert(['order_id' => $res, 'flw_time' => $created_time + 60 * 15, 'resp_pers' => $resp_pers['data'], 'create_time' => $created_time, 'update_time' => $created_time]);
//
//                db('remind')->insertGetId([
//                    'admin_id' => $this->us['user_id'],
//                    'order_id' => $res->order_id,
//                    'time' => time(),
//                    'stater' => 1,
//                    'tai' => 1,
//                ]);
//                $content = "店长输入的订单";
//                db('message')->insertGetId([
//                    'type' => 6,
//                    'content' => $content,
//                    'order_id' => $res->order_id,
//                    'time' => time(),
//                    'already' => 1,
//                    'user_id' => $this->us['user_id'],
//                ]);
//            }
            db()->commit();
            sendOrder($res);
            
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
    * 获取区
    */
    public function county() {
        $data = Authority::param(['cityName']);
        if ($data['cityName']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['cityName']}%"]])->value('city_id');
        } else {
            r_date(null, 300, '获取城市失败');
        }
        $county = db('county')->where(['city_id' => $city_id])->column('county');
        r_date($county, 200);
    }
    
    /**
     * @throws Exception
     * 提醒个数
     */
    public function Unread() {
        
        $coun1 = db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => 1, 'tai' => 1])->count();
        $coun2 = db('remind')->where(['admin_id' => $this->us['user_id'], 'stater' => 2, 'tai' => 1])->count();
        //        $coun3 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 3, 'tai' => 1])->count();
        //        $coun4 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 4, 'tai' => 1])->count();
        //        $coun5 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 5, 'tai' => 1])->count();
        //        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();
        //        $coun6 = db('remind')->where(['admin_id' =>  $this->us['user_id'], 'stater' => 7, 'tai' => 1])->count();
        
        $couns = ['zhu' => [//                0=>$coun1,
            //                1=>$coun2,
            0 => 0, 1 => 0,],];
        
        r_date($couns, 200);
        
    }
    
    /**
     * 修改地址
     * cate_id 二级id
     */
    public function edit_di(OrderModel $orderModel, House $house)
    {
        $data = $this->model->post(['order_id', 'county_id', 'addres', 'lat', 'lng', 'communityName', 'street', 'building', 'unit', 'room']);
        $orderModel->startTrans();
        try {

            if ($data['province_id']) {
                $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
            }
            if ($data['city_id']) {
                $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"]])->value('city_id');
            }
            if ($data['county_id']) {
                $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"]])->value('county_id');
            }
            if (!isset($province) || !isset($city_id)) {
                throw new Exception('未获取到地址,请重新输入');
            }
            $area=isset($county) ? $county : '';
            $house = $house->getHouse(['province' => $province, 'city' => $city_id, 'area' => isset($county) ? $county : '', 'communityName' => $data['communityName'], 'address' => $data['addres'], 'latitude' => $data['lat'], 'longitude' => $data['lng']]);
            $orderModel::update(['county_id' => isset($county) ? $county : '', 'addres' => $data['addres'], 'street' => $data['street'], 'building' => $data['building'], 'unit' => $data['unit'], 'room' => $data['room'], 'lat' => $data['lat'], 'lng' => $data['lng'], 'house_id' => $house, 'residential_quarters' => $data['communityName']], ['order_id' => $data['order_id']]);
            db('cc_scheme_label', \config('database.zong'))->where(['order_id' => $data['order_id']])->update(['house_id' => $house]);
            db('order_log')->insert(['admin_type' => 1, 'admin_id' => $this->us['user_id'],  'create_time' => time(), 'order_id' => $data['order_id'], 'content' => "修改了订单地址province:".$province.";city:".$city_id.";area:".$area.";addres:".$data['addres']]);
            db()->commit();
            sendOrder($data['order_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /**
     * 修改配送地址
     * cate_id 二级id
     */
    public function Distribution(OrderModel $orderModel) {
        $data           = $this->model->post();
        $agency_address = '';
        if (isset($data['agency_address'])) {
            $agency_address = $data['agency_address'];
            $res            = $orderModel::update(['agency_address' => $agency_address], ['order_id' => $data['order_id']]);
        } else {
            $agency_address = $data['goodsCategoryId'];
            $res            = $orderModel::update(['pro_id1' => $agency_address], ['order_id' => $data['order_id']]);
        }
        
        if ($res) {
            $orderSMS = json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                r_date([], 300, '编辑失败');
            }
            r_date([], 200, '新增成功');
        }
        
        r_date([], 300, '新增失败');
        
    }
    /**
     * 店长拒单
     */
    public function orderRejection()
    {
        $data = Authority::param(['reason', 'state', 'id']);
        $order_dispatch_user_auto = db('order_dispatch_user_auto', config('database.zong'))->where('id', $data['id'])->find();
        if ($data['state'] == 2) {

            if ($order_dispatch_user_auto['user_id'] != $this->us['user_id']) {
                r_date(null, 300, "拒单失败,自动派单店长已变更");
            }
            db('order_dispatch_user_auto', config('database.zong'))->where('id', $data['id'])->update(['user_id' => 0, 'user_limit_time' => 0]);
            db('order_dispatch_user_auto_info', config('database.zong'))->where('order_dispatch_user_auto_id', $data['id'])->where('user_id', $this->us['user_id'])->where('delete_time', 0)->update(['reason' => "拒单-" . $data['reason'], 'reason_type' => 2, 'update_time' => time()]);
        } else {
            $acceptOrders = acceptOrders($this->us['user_id'], $data['id']);
            if ($acceptOrders['code'] != 200) {
                r_date(null, 300, $acceptOrders['msg']);
            }
        }
        r_date($order_dispatch_user_auto['order_id'], 200);
    }
      /**
     * 店长拒单列表
     */
    public function orderRejectionList()
    {
    $list=db('order_dispatch_user_auto_info',config('database.zong'))
            ->field('FROM_UNIXTIME(order_dispatch_user_auto_info.create_time,"%Y-%m-%d %H:%i:%s")as createTime,CASE 
    WHEN reason_type = 1 THEN "超时自动" 
    WHEN reason_type = 2 THEN "手动" 
    ELSE "自动" 
  END   as method,reason')
        ->where('user_id', $this->us['user_id'])
         ->whereIn('reason_type', [1,2,3])
        ->where('create_time', '>=', strtotime('-60 days'))
         ->order('create_time desc')
        ->select();
        r_date(empty($list)?null:$list, 200);
    }
     
    /**
     * 店长接单弹窗拒绝原因
     */
    public function reasonForRejection()
    {

        $list =[
            ['id'=>1,'title'=>"近期忙"],
            ['id'=>2,'title'=>"今日没空"],
            ['id'=>3,'title'=>"其他"],
            ['id'=>4,'title'=>"距离太远"]
        ];
        r_date($list, 200);
    }
    /**
     * 获取渠道
     */
    public function get_my_qu() {
        $res = db('chanel')->field('id,title')->whereIn('id', [27, 28, 29, 30, 160])->where('type', 1)->select();
//        $res = db('chanel')->field('id,title')->whereIn('id', [28, 7, 4, 30, 13, 27, 31, 29])->where('type', 1)->select();
        foreach ($res as $k => $item) {
            
            
            $channel = db('channel_details')->where('type', 1);
            if ($item['id'] == 27) {
                $channel->where('id', '<>', 101);
            } elseif ($item['id'] == 29) {
                $channel->whereNotIn('id', '168,177');
            }
            $data = $channel->where('pid', $item['id'])->field('id,title')->order('id desc')->select();
            if (empty($data)) {
                $res[$k]['data'] = [];
            } else {
                $res[$k]['data'] = $data;
            }
            
        }
        r_date($res);
    }
    
    /**
     * 获取问题
     */
    public function get_my_wen() {
        $data = \request()->get();
        $res = db('goods_category')->field('goods_category.title,goods_category.id')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => 0, 'type' => 1])->select();
        if(isset($data['exist']) && $data['exist']==1){
        $exist=[[
            "title"=>"A级工地",
			"id"=>999
        ],[
            "title"=>"精选案例",
			"id"=>998
        ]];
            $res=array_merge($res,$exist);
        }
        r_date($res);
    }
    
    /**
     * 获取问题
     */
    public function getSecond() {
        $data = \request()->get();
        $res = db('goods_category')->field('goods_category.title,goods_category.id')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => $data['id'], 'type' => 1])->select();
        if(isset($data['exist']) && $data['exist']==1){
            $exist[]=[
                "title"=>"全部",
                "id"=>0
            ];
            $res=array_merge($exist,$res);
        }
        r_date($res);
    }
    
    /**
     * 智能报价
     */
    public function IntelligentQuotation() {
        $res = db('goods_category')->field('title,parent_id,id,type')->where(['pro_type' => 1, 'is_enable' => 1])->select();
        foreach ($res as $v) {
            if ($v['parent_id'] == 0 && $v['type'] == 2) {
                $op[] = $v;
            } else if ($v['type'] == 1) {
                $opp[] = $v;
            }
        }
        foreach ($op as $v) {
            $data = [];
            foreach ($opp as $item) {
                if ($v['id'] == $item['parent_id']) {
                    $data[] = $item;
                }
            }
            $da[] = ['title' => $v['title'], 'data' => $data,];
        }
        foreach ($da as $kef => $item) {
            $p = '';
            foreach ($item['data'] as $k => $it) {
                $p .= $it['id'] . ',';
            }
            $p     = substr($p, 0, -1);
            $res   = db('goods_category')->field('title,parent_id,id,type')->where(['pro_type' => 1, 'is_enable' => 1, 'parent_id' => ['in', $p]])->select();
            $daa[] = ['title' => $item['title'], 'data' => $res,];
        }
        r_date($daa);
    }
    
    /**
     * 获取比例
     */
    public function expense(Common $common) {
        $data = Request::instance()->post(['orderId']);
        $list = $common->coupon($data['orderId']);
        
        $order_setting = db('order_setting')->where('order_id', $data['orderId'])->find();
        r_date(['num' => isset($order_setting['max_expense_rate']) ? $order_setting['max_expense_rate'] / 100 : 0, 'agentRatio' => isset($order_setting['max_agent_expense_rate']) ? $order_setting['max_agent_expense_rate'] / 100 : 0, 'coupon' => count($list), 'newWarranty' => $order_setting['new_warranty_card']], 200);
    }
    
    /**
     * 获取智能报价
     */
    public function smartOptions() {
        $data         = Request::instance()->post(['id']);
        $res          = db('goods_category')->field('mandatory,optional,id,kind')->where(['id' => ['in', $data['id']], 'pro_type' => 1, 'is_enable' => 1])->select();
        $mandatory    = '';
        $optional     = '';
        $Intelligence = '';
        foreach ($res as $i) {
            if (!empty($i['mandatory']) && $i['kind'] == 2) {
                $Intelligence .= $i['mandatory'] . ',';
            }
            if (!empty($i['mandatory']) && $i['kind'] == 1) {
                $mandatory .= $i['mandatory'] . ',';
            }
            if (!empty($i['optional']) && $i['kind'] == 1) {
                $optional .= $i['optional'] . ',';
            }
        }
        $pr = [];
        if (!empty($mandatory)) {
            $mandatory = substr($mandatory, 0, -1);
            $rdetailed = db('detailed')->where(['serial' => ['in', $mandatory], 'tao' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k => $l) {
                $pr[$k]['projectId']    = $l['detailed_id'];
                $pr[$k]['projectMoney'] = $l['artificial'];
                $pr[$k]['projectTitle'] = $l['detailed_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 1;
                $pr[$k]['type']         = 1;
                unset($rdetailed[$k]);
            }
            
        }
        
        if (!empty($Intelligence)) {
            $Intelligence = substr($Intelligence, 0, -1);
            $rdetailed    = db('detailed')->whereIn('serial', $Intelligence)->where('tao', 0)->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            
            foreach ($rdetailed as $k => $l) {
                $prr[$k]['projectId']    = $l['detailed_id'];
                $prr[$k]['projectMoney'] = $l['artificial'];
                $prr[$k]['projectTitle'] = $l['detailed_title'];
                $prr[$k]['title']        = $l['title'];
                $prr[$k]['number']       = $l['number'];
                $prr[$k]['tao']          = 1;
                $prr[$k]['type']         = 2;
                unset($rdetailed[$k]);
            }
            
            $pr = array_merge($pr, $prr);
            
        }
        
        $option = [];
        if (!empty($optional)) {
            $optional  = substr($optional, 0, -1);
            $rdetailed = db('detailed')->where(['serial' => ['in', $optional], 'tao' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,number')->select();
            foreach ($rdetailed as $k => $l) {
                $option[$k]['projectId']    = $l['detailed_id'];
                $option[$k]['projectMoney'] = $l['artificial'];
                $option[$k]['projectTitle'] = $l['detailed_title'];
                $option[$k]['title']        = $l['title'];
                $option[$k]['number']       = $l['number'];
                $option[$k]['tao']          = 1;
                $option[$k]['type']         = 1;
                unset($rdetailed[$k]);
            }
        }
        r_date(['mandatory' => $pr, 'nonEssentialElection' => $option,]);
    }
    
    /*
     * 获取城市
     */
    public function city(\app\api\model\Common $common) {
        $data = Request::instance()->post();
        $list = $common->obtainCity($data['cityName'] ?? '');
        r_date($list, 200);
    }
    
    /*
     * 获取城市
     */
    public function latelyCity(\app\api\model\Common $common) {
        
        $list = $common->obtainCity('', 2);
        
        r_date($list, 200);
        
    }
    
    /**
     * 获取标题
     */
    public function Material() {
        $res = db('stock')->field('id,company,stock_name,latest_cost,type,class_table')->select();
        $po  = array_merge(array_unique(array_column($res, 'type')));
        foreach ($po as $k => $v) {
            $data = [];
            foreach ($res as $value) {
                if ($v == $value['type']) {
                    $data['title']  = $value['class_table'];
                    $data['type']   = $v;
                    $data['data'][] = $value;
                    $data['count']  = count($data['data']);
                }
            }
            unset($data['data']);
            $r[] = $data;
        }
        
        $custom          = [];
        $cpurchase       = [];
        $custom_material = db('custom_material')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where('number', 'neq', 0)->field('id,company,stock_name,latest_cost')->select();
        
        
        $custom[0]['title'] = '自购入库材料';
        $custom[0]['type']  = 0;
        $custom[0]['count'] = count($custom_material);
        
        $cpurchase_usage = db('purchase_usage')->where(['store_id' => $this->us['store_id']])->where('status', 3)->where('number', 'neq', 0)->field('id,company,stock_name,latest_cost')->select();
        
        $cpurchase[0]['title'] = '采购入库材料';
        $cpurchase[0]['type']  = 99;
        $cpurchase[0]['count'] = count($cpurchase_usage);
        
        r_date(array_merge(array_merge($r, $custom), $cpurchase), 200);
    }
    
    /**
     * 获取列表
     */
    public function Material_list() {
        $data = Request::instance()->post(['type']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')->field('id,company,stock_name,latest_cost,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->select();
        } else {
            $custom = db('stock')->field('id,company,stock_name,latest_cost')->where('type', $data['type'])->select();
        }
        
        
        r_date($custom, 200);
    }

    //材料费用提交
    public function material_usage(Common $common)
    {
        $data            = Request::instance()->post();
        $data['storeId'] = $this->us['store_id'];
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点中，无法领用，请盘点完成后操作');
        }
        $common->isStart($data['order_id'],$this->us);
        $material_usage = json_decode($data['materialJson'], true);
        db()->startTrans();
        try {
            $orderList = db('order')->where('order_id', $data['order_id'])->find();
            $order_setting = db('order_setting')->where('order_id', $data['order_id'])->find();
            $keyss     = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->value('valuess');
            if (!empty($keyss)) {
                $keyss = explode(',', $keyss);
            }

            $p                  = 0;
            $material_usageList = [];
            foreach ($material_usage as $datum) {
                if ($datum['square_quantity'] == 0) {
                    throw new Exception('材料领取数量不能为0');
                }
                if (in_array($datum['invclasscode'], $keyss) && !empty($orderList['settlement_time'])) {
                    throw new Exception('订单代购主材已结算');
                }
                if (!in_array($datum['invclasscode'], $keyss) && !empty($orderList['cleared_time'])) {
                    throw new Exception('该订单主材已结算');
                }

                $square_quantity = db('material_usage')->where('order_id', $data['order_id'])->where('status', 1)->where('code', $datum['Material_id'])->sum('square_quantity');
                if ($datum['square_quantity'] < 0) {
                    if ($square_quantity < abs($datum['square_quantity'])) {
                        throw new Exception('退回数量超出了本单领用的数量，无法退回，请核对数量后正确退回本单没有领用该材料，无法退回');
                    }
                }
                $op  = u8queryForStoreId($datum['Material_id'], $orderList['store_id']);
                $u8c = json_decode($op, true);
                if ($u8c['status'] == 'success') {
                    $number = $u8c['data'];
                    if (!is_array($number)) {
                        $number = json_decode($u8c['data'], true);
                    }

                    if ($number['datas'][0]['nnum'] - $datum['square_quantity'] < 0) {
                        throw new Exception('库存不足');
                    }
                    $pp = [
                        'order_id' => $data['order_id'],
                        'material_name' => $datum['material_name'],
                        'Material_id' => 0,
                        'square_quantity' => $datum['square_quantity'],
                        'unit_price' => $datum['unit_price'],
                        'type' => $datum['type'],
                        'company' => $datum['company'],
                        'total_price' => round($datum['unit_price'] * $datum['square_quantity'], 2),
                        'user_id' => $this->us['user_id'],
                        'created_time' => time(),
                        'shopowner_id' => $this->us['user_id'],
                        'adopt' => time(),
                        'status' => 1,
                        'total_profit' => $datum['unit_price'] * $datum['square_quantity'],
                        'types' => 1,
                        'code' => $datum['Material_id'],
                        'invclasscode' => $datum['invclasscode']
                    ];
                    $material_usage = db('material_usage')->insertGetId($pp);
                    db('usage_record')->insertGetId([
                        'id' => $material_usage,
                        'type' => $datum['type'],
                        'user_id' => $this->us['user_id'],
                        'number' => $datum['square_quantity'],
                        'created_time' => time(),
                        'order_id' => $data['order_id'],
                        'original_number' => $datum['square_quantity'],
                        'unified' => $datum['Material_id']
                    ]);
                    $material_usageList[] = ['Material_id' => $datum['Material_id'], 'square_quantity' => $datum['square_quantity'], 'unit_price' => $datum['unit_price'], 'id' => $material_usage];
                    $p                    += $pp['total_price'];
                }
            }
            if ($orderList['business_type'] == 2 && $order_setting['stop_material_usage'] == 0) {
                $capital = db('capital')->where('types', 1)->where('enable', 1)->where('ordesr_id', $data['order_id'])->where('agency',  0)->sum('base_contract_price');
                $moneyList = db('reimbursement')->where('order_id', $data['order_id'])->where('status', '<>', 2)->where('classification', '<>', 4)->sum('money');
                $material_usageSUm = db('material_usage')->whereNotIn('invclasscode', $keyss)->where('order_id', $data['order_id'])->whereNotIn('id',array_column($material_usageList,'id'))->where('status', '<>', 2)->sum('total_price');
                if (bcadd(bcadd($material_usageSUm, $moneyList, 2), $p, 2) > $capital) {
                    throw new Exception('可使用发包价余额为:' . bcsub($capital, bcadd($material_usageSUm, $moneyList, 2), 2) . ':当前提交金额为:' . $p . '，已超出，请更改或删减。');
                }
            }
            if (empty($material_usageList)) {
                throw new Exception('没有新的材料领用');
            }
            // U8cForList($material_usageList, $data['order_id'], $this->us['store_id'], 1);

            if ((string)$p != $data['allMoney']) {
                throw new Exception('金额错误');
            }
            db()->commit();
            foreach ($material_usageList as $i) {
                $inter    = u8insertU8c($orderList['store_id'], $data['order_id'], $i['square_quantity'], $i['Material_id'], 0, $i['id']);
                $U8cinter = json_decode($inter, true);
                if ($U8cinter['status'] == 'success') {
                    //材料成本售价
                    $materialCostSellingPrice = $U8cinter['data']['materialCostSellingPrice'];
                    //材料成本单价
                    $materialCostUnitPrice = $U8cinter['data']['materialCostUnitPrice'];

                    $total_price      =  bcmul($datum['square_quantity'], $materialCostSellingPrice, 2);
                    $total_profit      =  bcmul($datum['square_quantity'], $materialCostUnitPrice, 2);
                    //材料领用
                    db('material_usage')->where(['id' => $material_usage])->update(['unit_price' => $materialCostSellingPrice, 'total_price' => $total_price, 'total_profit' => $total_profit]);
                }
            }
            sendOrder($data['order_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            journal(['url' => '店长审核报错', 'data' => $e->getMessage()]);
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /*
     * 费用报销
     */
    public function reimbursement(Approval $approval, OrderModel $orderModel, Common $common, MaterialScience $materialScience) {
        
        $data = Request::instance()->post();
        
        db()->startTrans();
        try {
            if ($data['type'] == 2 || $data['type'] == 1 || $data['type'] == 3) {
                if (empty($data['receiptNumber'])) {
                    throw new Exception('收据编号不能为空');
                }
                
            }
            $orderList = db('order')->field('personal.num,order.cleared_time,order.settlement_time,order.business_type')->join('personal', 'order.tui_jian=personal.personal_id', 'left')->join('contract', 'order.order_id=contract.orders_id', 'left')->where('order.order_id', $data['order_id'])->find();
            
            $my_string                   = explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $data['work_wechat_user_id'] = $this->us['work_wechat_user_id'];
            $data['reserve']             = $this->us['reserve'];
            $capital_id                  = json_decode($data['mainMaterialIds'], true);
            $mainMaterialId              = array_column($capital_id, 'mainMaterialId');
            $s                           = '';
            $io                          = implode(',', $mainMaterialId);
            $capital                     = db('capital')->whereIn('capital_id', $io)->field('class_b,to_price,company,(labor_cost+labor_cost_material) as labor_cost,labor_cost_reimbursement,capital_id,projectId')->select();
            $reimbursement_capital_beforehand                     = db('reimbursement_capital_beforehand')->where('delete_time',0)->whereIn('capital_id', $io)->sum('beforehand_money');
            $appUserOrderCapital        = db('app_user_order_capital')->whereIn('capital_id', $io)->whereNull('deleted_at')->field('sum(personal_price+cooperation_price) as  total_price')->select();
            $appUserOrderCapital                  = empty($appUserOrderCapital[0]['total_price']) ? 0 : $appUserOrderCapital[0]['total_price'];
            $order_times                = Db::table('order_times')->where('order_id', $data['order_id'])->field('change_work_time')->find();
            $mo=1;
            if (($data['type'] == 1 || $data['type'] == 3) && (($order_times['change_work_time']<1720724400 && !in_array('10039',array_column($capital,'projectId')) && !in_array('10040',array_column($capital,'projectId'))) || $order_times['change_work_time']>1720724400) && $mo==0) {
                //总得剩余额度
               $money= (string)round(array_sum(array_column($capital,'labor_cost'))-array_sum(array_column($capital,'labor_cost_reimbursement'))-$reimbursement_capital_beforehand-$appUserOrderCapital,3);
                foreach ($capital as $l => $item) {
                    $s                      .= $item["class_b"] . '-￥' . $item["to_price"] . ',';
                   
                }
                if($money<$data['money']){
                    $chao=$data['money']-$money;
                    r_date(null,302,'勾选清单剩余可报销金额为【'.$money.'元】，您输入的金额已超出【'.$chao.'】，若仍然要报销，需要在施工安排功能中，对关联清单增加超限人工费');
                }
            }
            
            $s               = substr($s, 0, -1);
            $data['content'] = $data['remarks'] . ',' . $s;
            if ($data['type'] == 4) {
                $s             = '';
                $money         = array_column($capital_id, 'money');
                $data['money'] = array_sum($money);
            }
            $order_setting = db('order_setting')->where('order_id', $data['order_id'])->find();
            
            if ($data['type'] != 4) {
                $MultimediaResourcesType = 11;
                $common->isStart($data['order_id'],$this->us);
                if (!empty($orderList['cleared_time'])) {
                    throw new Exception('该订单已结算');
                }
                $offer = $orderModel->TuiNewOffer($data['order_id']);
                //签约金额
                if ($offer['amount'] != 0) {
                    $moneyList = db('reimbursement')->where('order_id', $data['order_id'])->where('status', '<>', 2)->where('classification', '<>', 4)->sum('money');
                    $payment   = $common::order_for_payment($data['order_id']);
                    if (!empty($order_setting)) {
                        if($orderList['business_type'] ==2 &&  $order_setting['stop_main_reimbursement']==0){
                                $capital=db('capital')->where('types', 1)->where('enable', 1)->where('ordesr_id', $data['order_id'])->where('agency',  0)->sum('base_contract_price');
                                 $sysConfig       = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
                                $material_usage = db('material_usage')->whereIn('invclasscode', $sysConfig)->where('order_id', $data['order_id'])->where('status', '<>', 2)->sum('total_price');
                              if (bcadd(bcadd($material_usage,$moneyList,2),$data['money'],2)>$capital) {
                                throw new Exception('可使用发包价余额为:'.bcsub($capital,bcadd($material_usage,$moneyList,2),2).':当前提交金额为:'.$data['money'].'，已超出，请更改或删减。');
                            }  
                        }
                        if ($order_setting['max_reimbursement_rate'] == 0) {
                            if ($moneyList + $data['money'] > $payment[4] && $order_setting['payment_type'] != 3) {
                                // $max_reimbursement_rate = $payment[4] - ($moneyList + $data['money']);
                                throw new Exception('总报销金额'.($moneyList + $data['money']).'不能超出主合同收款金额' .  $payment[4] . '元，请在企业微信审批里提交“报销请款超限申请”');
                            }
                            if ($data['money'] > 100) {
                                $payment = $common::order_for_payment($data['order_id']);
                                if ($payment[0] / $offer['amount'] < 0.3) {
                                    throw new Exception('项目收款小于30%,无法使用报销,请严格按照收款制度进行收款');
                                }
                                
                            }
                        } elseif ($order_setting['max_reimbursement_rate'] > 0) {
                            if (round(($moneyList + $data['money']) / $offer['amount'] * 100, 2) >= $order_setting['max_reimbursement_rate']) {
                                throw new Exception('报销金额不能大于主合同收款金额申请的' . $order_setting['max_reimbursement_rate'] . '%');
                            }
                        
                        }
                    } else {
                        if ($moneyList + $data['money'] > $payment[4] && $order_setting['payment_type'] != 3) {
                            throw new Exception('报销金额不能大于收款金额');
                        }
                        if ($data['money'] > 100) {
                            $payment = $common::order_for_payment($data['order_id']);
                            if ($payment[0] / $offer['amount'] < 0.3) {
                                throw new Exception('项目收款小于30%,无法使用报销,请严格按照收款制度进行收款');
                            }
                            
                        }
                    }
                    
                    
                } else {
                    throw new Exception('主合同金额为0,不能报销');
                }
            } else {
                if (!empty($orderList['settlement_time'])) {
                    throw new Exception('该订单已结算');
                }
                $MultimediaResourcesType = 12;
                $offer                   = $orderModel->TotalProfit($data['order_id']);
                //签约金额
                if ($offer['agencyMoney'] != 0) {
                    $data['secondary_classification'] = 14;
                    $moneyListAgent                   = db('reimbursement')->where('order_id', $data['order_id'])->where('status', '<>', 2)->where('classification', 4)->sum('money');
                    if (!empty($order_setting)) {
                        if ($order_setting['max_agent_reimbursement_rate'] == 0) {
                            // $payments = $common::order_for_payment($data['order_id']);
                            // if ($moneyListAgent + $data['money'] > $payments[5]) {
                            //     throw new Exception('主材报销金额不能大于收款金额');
                            // }
                            
                            //  if ($data['money'] > 100) {
                            $payment = $common::order_for_payment($data['order_id']);
                            
                            if ($payment[1] + $payment[1] * 0.2 < $moneyListAgent + $data['money'] && $order_setting['payment_type'] != 3) {
                                throw new Exception('请款金额超出代购已收款金额，按照当前代购已收款金额，你本次最多可请款' . ($payment[1] + $payment[1] * 0.2) . "元，如果仍要超额请款，请前往企业微信审批里提交“报销请款超限申请”");
                                // }
                                
                            }
                        } elseif ($order_setting['max_agent_reimbursement_rate'] > 0) {
                            if (round(($moneyListAgent + $data['money']) / $offer['agencyMoney'] * 100, 2) >= $order_setting['max_agent_reimbursement_rate']) {
                                throw new Exception('报销金额不能大于代购收款金额申请的' . $order_setting['max_agent_reimbursement_rate'] . '%');
                            }
                        }
                    } else {
                        $payments = $common::order_for_payment($data['order_id']);
                        if ($moneyListAgent + $data['money'] > $payments[5]) {
                            throw new Exception('主材报销金额不能大于收款金额');
                        }
                        if ($data['money'] > 100) {
                            $payment = $common::order_for_payment($data['order_id']);
                            if ($payment[1] / $offer['agencyMoney'] < 0.49) {
                                throw new Exception('主材收款小于50%，无法使用请款，请严格按照收款进度进行收款');
                            }
                            
                        }
                    }
                } else {
                    throw new Exception('代购合同金额为0,不能报销');
                }
            }
            $reimbursementList = db('reimbursement')->where(['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money']])->find();
            if (!empty($reimbursementList)) {
                throw new Exception('名称和金额重复');
            }
            $op = ['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money'], 'voucher' => !empty($data['img']) ? serialize($my_string) : '', 'created_time' => time(), 'user_id' => $this->us['user_id'], 'status' => 0, 'sp_no' => '', 'content' => $data['content'], 'classification' => $data['type'], 'submission_time' => time(), 'shopowner_id' => $this->us['user_id'], 'capital_id' => $io, 'payment_notes' => $data['payment_notes'], 'secondary_classification' => isset($data['secondary_classification']) ? $data['secondary_classification'] : 0];
            $titles=$materialScience->list_reimbursement_type(2);
            $kl=[];
            foreach ($titles as $v){
                if($v['type']==$data['type']){
                    $kl= $v;
                }
            }
            
            if(!isset($kl['data'])){
                $op['secondary_classification'] =0;
            }
            $reimbursementId = db('reimbursement')->insertGetId($op);
            if (($data['type'] == 1 || $data['type'] == 3) && (($order_times['change_work_time']<1720724400 && !in_array('10039',array_column($capital,'projectId')) && !in_array('10040',array_column($capital,'projectId'))) || $order_times['change_work_time']>1720724400) && $mo==0) {
                $reimbursement_capital_beforehand = [];
                foreach ($capital as $k => $item) {
                    $appUserOrderCapital        = db('app_user_order_capital')->where('capital_id', $item['capital_id'])->whereNull('deleted_at')->field('sum(personal_price+cooperation_price) as  total_price')->select();
                    $reimbursementCapitalBeforehand                     = db('reimbursement_capital_beforehand')->where('delete_time',0)->where('capital_id', $item['capital_id'])->sum('beforehand_money');
                    $appUserOrderCapital                  = empty($appUserOrderCapital[0]['total_price']) ? 0 : $appUserOrderCapital[0]['total_price'];
                    $dange               = (string)round($item['labor_cost']-$item['labor_cost_reimbursement']-$appUserOrderCapital-$reimbursementCapitalBeforehand,3);
                    $bi=(string)($dange/$money);
                    $beforehand_money = round($bi * $data['money'], 2);
                    if(($data['money']- (string)array_sum(array_column($reimbursement_capital_beforehand,'beforehand_money'))) <0){
                        $beforehand_money=0;
                        $last=$data['money'] - (string)array_sum(array_column($reimbursement_capital_beforehand, 'beforehand_money'));
                        $reimbursement_capital_beforehand[count($reimbursement_capital_beforehand)-1]['beforehand_money']=$reimbursement_capital_beforehand[count($reimbursement_capital_beforehand)-1]['beforehand_money']-abs($last);
                    }
                    if ($k != 0 && $k == count($capital) - 1 && ($data['money']- (string)array_sum(array_column($reimbursement_capital_beforehand,'beforehand_money'))) >0) {
                        $beforehand_money = $data['money'] - array_sum(array_column($reimbursement_capital_beforehand, 'beforehand_money'));
                    }
                    $reimbursement_capital_beforehand[] = ['capital_id' => $item['capital_id'], 'reimbursement_id' => $reimbursementId, 'beforehand_money' => $beforehand_money, 'create_time' => time()];
                }
                db('reimbursement_capital_beforehand')->insertAll($reimbursement_capital_beforehand);
            }
            $common->MultimediaResources($data['order_id'], $this->us['user_id'], !empty($data['img']) ? $my_string : [], $MultimediaResourcesType);
            if ($reimbursementId) {
                
                if ($data['type'] == 4) {
                    
                    foreach ($capital_id as $value) {
                        if (empty($value['receiptNumber'])) {
                            throw new Exception('收据编号不能为空');
                        }
                        if (!empty($value['money'])) {
                            db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId, 'capital_id' => $value['mainMaterialId'], 'bank_id' => $value['supplierId'], 'money' => $value['money'], 'receipt_number' => isset($value['receiptNumber']) ? $value['receiptNumber'] : '']);
                        }
                        
                    }
                    
                } else {
                    db('reimbursement_relation')->insertGetId(['reimbursement_id' => $reimbursementId, 'capital_id' => $io, 'bank_id' => $data['bankCardId'], 'money' => $data['money'], 'receipt_number' => isset($data['receiptNumber']) ? $data['receiptNumber'] : '']);
                }
                $title = array_search($data['type'], array_column($materialScience->list_reimbursement_type(2), 'type'));
                $title = $this->us['username'] . $materialScience->list_reimbursement_type(2)[$title]['name'] . '报销';
                db()->commit();
                sendOrder($data['order_id']);
                $approval->Reimbursement($reimbursementId, $title, $this->us['username'], $data['type']);
                r_date(null, 200);
            }
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
            
        }
        
    }
    
    /*
     * 费用报销提示
     */
    public function expenseReimbursementPrompt(Capital $capital) {
        $data              = Request::instance()->post();
        $envelopes_id      = \db('envelopes')->where('ordesr_id', $data['orderId'])->where('type', 1)->value('envelopes_id');
        $u8c_invprice      = db('u8c_invprice', config('database.zong'))->where('store_id', $this->us['store_id'])->select();
        $labor_cost_config = db('labor_cost_config', config('database.zong'))->where('city_id', config('cityId'))->find();
        $l                 = $capital->capitalCheck($data['orderId'], $envelopes_id);
        $capitalId         = isset($data['capitalId']) ? json_decode($data['capitalId'], true) : [];
        $price             = 0;
        $result            = [];
        foreach ($l as $k => $v) {
            $zhuMaterialCost = 0;
            if (!empty($v['content'])) {
                $content = json_decode($v['content'], true);
                foreach ($content as $item) {
                    foreach ($u8c_invprice as $value) {
                        if ($item['invcode'] == $value['invcode'] && $item['sum'] == 0) {
                            $content[$k]['sum'] = bcmul(bcmul($item['recommended_quantity'], $value['nabprice'], 2), $v['square'], 2);
                            $zhuMaterialCost    += $content[$k]['sum'];
                            
                        }
                    }
                    
                }
                $v['content'] = json_encode($content);
            }
            if (!empty($capitalId) && in_array($v['capitalId'], $capitalId)) {
                $price += $v['zhuLaborCost'];
            }
            $v['zhuMaterialCost']         = $zhuMaterialCost;
            $result[$v['envelopes_id']][] = $v;
        }
        $zhuSum        = 0;
        $daiSum        = 0;
        $zhuLaborCosts = 0;
        $title         = '';
        if ($result) {
            foreach ($result as $k => $list) {
                $zhu           = array_sum(array_column($list, 'main_price')) - $result[$k][0]['give_money'] + $result[$k][0]['expense'];//祝主合同清单
                $zhuLaborCosts += array_sum(array_column($list, 'zhuLaborCost'));
                $zhuSum        += bcmul($zhu, ($labor_cost_config['main_contract_measure_ratio'] / 100), 2);//措施费
                $zhuSum        += array_sum(array_column($list, 'zhuMaterialCost'));//材料费
                
                $dai             = array_sum(array_column($list, 'agent_price')) - $result[$k][0]['purchasing_discount'] + $result[$k][0]['purchasing_expense'];
                $daiMeasurefee   = bcmul($dai, ($labor_cost_config['agency_contract_measure_ratio'] / 100), 2);
                $daiLaborCost    = array_sum(array_column($list, 'daiLaborCost'));
                $daiMaterialCost = array_sum(array_column($list, 'daiMaterialCost'));//材料费
                if ($dai != 0) {
//                    $estimate = round(($daiLaborCost + $daiMeasurefee + $daiMaterialCost) / $dai, 4) * 100;
//                    if ($estimate < 60) {
//                        $daiMaterialCost = array_sum(array_column($list, 'agent_price')) * 0.6;
//                    }
                    $estimate = $daiLaborCost + $daiMaterialCost;
                    if ($estimate == 0) {
                        $daiMaterialCost = array_sum(array_column($list, 'agent_price')) * 0.6;
                        $daiMeasurefee   = 0;
                    }
                }
                $daiSum += $daiMaterialCost;
                $daiSum += $daiLaborCost;
                $daiSum += $daiMeasurefee;//材料费
            }
            $bi = 0;
            switch ($data['type']) {
                case 1 :
                    $moneyList = db('reimbursement')->where('order_id', $data['orderId'])->where('status', '<>', 2)->whereIn('classification', [1, 2, 7])->sum('money');
//
//                    if($price >0 && $price<$data['money']){
//                        $title = '您输入的金额超出可报销范围'.$price.'元，若仍然要报销，需要增加超限人工费';
//                    }else
                    if ($zhuSum != 0) {
                        $bi = round(($moneyList + $data['money']) / $zhuSum, 2);
                    }
                    if ($bi > 1) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList) . '，超过预估金额￥' . $zhuSum . '额度的￥' . ($moneyList + $data['money'] - $zhuSum) . '，占比' . ($bi * 100) . '%，报销可能被驳回。';
                    } elseif (0.8 <= $bi && 1 >= $bi) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList) . '，达到预估金额￥' . $zhuSum . '预估的' . ($bi * 100) . '%。';
                    }
                    break;
                case 2:
                case 7:
                    $moneyList = db('reimbursement')->where('order_id', $data['orderId'])->where('status', '<>', 2)->whereIn('classification', [1, 2, 7])->sum('money');
                    if ($zhuSum != 0) {
                        $bi = round(($moneyList + $data['money']) / $zhuSum, 2);
                    }
                    if ($bi > 1) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList) . '，超过预估金额￥' . $zhuSum . '额度的￥' . ($moneyList + $data['money'] - $zhuSum) . '，占比' . ($bi * 100) . '%，报销可能被驳回。';
                    } elseif (0.8 <= $bi && 1 >= $bi) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList) . '，达到预估金额￥' . $zhuSum . '预估的' . ($bi * 100) . '%。';
                    }
                    
                    break;
                case 3:
                    $moneyList      = db('reimbursement')->where('order_id', $data['orderId'])->where('status', '<>', 2)->where('classification', 3)->sum('money');
                    $personal_price = db('app_user_order_capital')->where('order_id', $data['orderId'])->whereNull('deleted_at')->sum('personal_price');
                    if ($zhuLaborCosts != 0) {
                        $bi = round(($moneyList + $data['money'] + $personal_price) / $zhuLaborCosts, 2);
                    }
                    
                    if ($price > 0 && $price < $data['money']) {
                        $title = '您输入的金额超出可报销范围' . $price . '元，若仍然要报销，需要增加超限人工费';
                    } elseif ($bi > 1) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '与已经标记的师傅工资￥' . $personal_price . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList + $personal_price) . '，超过预估金额￥' . $zhuLaborCosts . '额度的￥' . (($moneyList + $data['money'] + $personal_price) - $zhuLaborCosts) . '，占比' . ($bi * 100) . '%，报销可能被驳回。';
                    } elseif (0.8 <= $bi && 1 >= $bi) {
                        $title = '已经提交报销的金额（含未过审）与已经标记的师傅工资￥' . $moneyList . '，加上当前报销金额合计为￥' . $data['money'] . '，达到预估金额￥' . $zhuSum . '预估的' . ($bi * 100) . '%。';
                    }
                    break;
                case 4:
                    $moneyList = db('reimbursement')->where('order_id', $data['orderId'])->where('status', '<>', 2)->where('classification', 4)->sum('money');
                    if ($daiSum != 0) {
                        $bi = round(($moneyList + $data['money']) / $daiSum, 2);
                    }
                    
                    if ($bi > 1) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList) . '，超过预估金额￥' . $daiSum . '额度的￥' . ($data['money'] + $moneyList - $daiSum) . '，占比' . ($bi * 100) . '%，报销可能被驳回。';
                    } elseif (0.8 <= $bi && 1 >= $bi) {
                        $title = '已经提交报销的金额（含未过审）￥' . $moneyList . '，加上当前报销金额合计为￥' . ($data['money'] + $moneyList) . '，达到预估金额￥' . $daiSum . '预估的' . ($bi * 100) . '%。';
                    }
                    break;
            }
        }
        
        r_date($title, 200);
        
    }
    
    /*
     * 供应商添加
     */
    public function agencyAdd() {
        $data     = Request::instance()->post();
        $province = '';
        $city_id  = '';
        $county   = '';
        if ($data['province_id']) {
            $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
        }
        if ($data['county_id']) {
            $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
        }
        $agency_name = db('agency', config('database.zong'))->where(['agency_name' =>$data['agencyName']])->find();
        if(!empty($agency_name)){
            r_date(null,300,'已经有同名供应商，可搜索后指派，无需重新添加');
        }
        if (isset($data['supplierId']) && !empty($data['supplierId']) != 0) {
            $count = db('agency', config('database.zong'))->where(['agency_id' => $data['supplierId']])->value('collection_number');
            
            if ($count == $data['collectionNumber']) {
                r_date(null, 300, '请勿重复录入');
            }
            $res = db('agency', config('database.zong'))->where('agency_id', $data['supplierId'])->update(['agency_name' => $data['agencyName'], 'rangess' => 1, 'province' => $province, 'city' => $city_id, 'area' => $county,  'product_notes' => $data['productNotes'], 'belonging_to' => $data['belongingTo'], 'scope_business' => $data['scopeBusiness'], 'contacts' => $data['contacts'], 'telephone' => $data['telephone'], 'account_type' => $data['accountType'], 'collection_name' => $data['collectionName'], 'collection_number' => $data['collectionNumber'], 'bank' => $data['bank'], 'bank_of_deposit' => $data['bankOfDeposit'],'cooperation_type'=>2,'detailed_category_id'=>$data['business']]);
            $res= $data['supplierId'];
        } else {
            $res = db('agency', config('database.zong'))->insertGetId(['agency_name' => $data['agencyName'], 'user_id' => $this->us['user_id'], 'store_id' => $this->us['store_id'], 'rangess' =>1, 'province' => $province, 'city' => $city_id, 'area' => $county, 'product_notes' => $data['productNotes'], 'belonging_to' => $data['belongingTo'], 'scope_business' => $data['scopeBusiness'], 'contacts' => $data['contacts'], 'telephone' => $data['telephone'], 'account_type' => $data['accountType'], 'collection_name' => $data['collectionName'], 'collection_number' => $data['collectionNumber'], 'bank' => $data['bank'], 'bank_of_deposit' => $data['bankOfDeposit'], 'state' => 0, 'creation_time' => time(), 'random_number' => date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 2),'cooperation_type'=>2,'detailed_category_id'=>$data['business'],'developer_name'=>$this->us['username']]);
    
            //            db('agency_business', config('database.zong'))->insertAll($businessArray);
            db('agency_business_scope', config('database.zong'))->insert(['agency_id'=>$res, 'city_id'=>$data['scopeBusiness']]);
        }
        
        if ($res === false) {
            r_date(null, 300);
        }
        r_date(['agency_id' => $res, 'agency_name' => $data['agencyName']], 200);
    }
    
    
    /*
     * 代购主材合作公司
     */
    public function PartnerCompany(Approval $approval) {
        $parem     = Request::instance()->post();
        $common    = new \app\api\model\Common();
        $agency_id = db('agency_business_scope', config('database.zong'))->where('city_id', config('cityId'))->column('agency_id');
        $data      = db('agency', config('database.zong'))->join('agency_user', 'agency_user.agency_id=agency.agency_id', 'left')->join('province p', 'agency.province=p.province_id', 'left')->join('city c', 'agency.city=c.city_id', 'left')->join('user', 'agency.user_id=user.user_id', 'left')->join('store', 'agency.store_id=store.store_id', 'left')->join('county y', 'agency.area=y.county_id', 'left');
        if (isset($parem['title']) && $parem['title'] != '') {
            $data->where(function ($query) use ($parem) {
                $query->whereOr('agency.agency_name', 'Like', "%{$parem['title']}%")->whereOr('agency.contacts', 'Like', "%{$parem['title']}%")->whereOr('agency.telephone', 'Like', "%{$parem['title']}%");
            });
        }
        if (isset($parem['projectId']) && json_decode($parem['projectId'], true) != '') {
            $projectId = json_decode($parem['projectId'], true);
            $projectId = array_column($projectId, 'projectId');
           $detailed_category_id=db('detailed')->whereIn('detailed_id', $projectId)->where('user_id','<>',0)->column('detailed_category_id');
           $agencyId=0;
           $detailed_agencyList = [];
           $detailed_agency     = [];
//            if(!empty($detailed_category_id)){
//                $agencyId=db('agency', config('database.zong'))
//                    ->where(function ($query) use ($detailed_category_id) {
//                        foreach ($detailed_category_id as $value) {
//                            $query->whereOrRaw("FIND_IN_SET({$value}, agency.detailed_category_id) > 0", [], 'string');
//                        }
//                    })->where('creation_time','>','1730044800')->column('agency_id');
//            }
            if(!empty($detailed_category_id)){
                $agencyId=db('agency', config('database.zong'))->where('user_id','<>',0)->where('creation_time','>','1730044800')->column('agency_id');
            }
           
            if (count($projectId) == 1) {
                $detailed_agency     = db('detailed_agency')->whereIn('detailed_id', $projectId)->column('agency_id');
                $detailed_agencyList = $detailed_agency;
            } else {
//                $projectId = array_unique($projectId);
               
                foreach ($projectId as $k => $value) {
                    $fruits = Db::table('detailed_agency')->where('detailed_id', $value)->column('agency_id');
                    if ($k == 0) {
                        $detailed_agency = $fruits;
                    } else {
                        $o                   = array_intersect($detailed_agency, $fruits);
                        $detailed_agencyList = array_merge($detailed_agencyList, $o);
                    }
                    
                }
            }
           if(!empty($detailed_agencyList)){
            $agencyId=0;
           } 
            $data->where(function ($quer) use ($detailed_agencyList,$agencyId){
                $quer-> whereIn('agency.agency_id', $detailed_agencyList)->whereOr(function ($oe)use($agencyId){
                    $oe->whereIn('agency.agency_id', $agencyId);
                });
            });
        
        }
        $data->where('agency.state', '=', 1);
        $data->whereIn('agency.agency_id', $agency_id);
        $list = $data->field('agency.agency_id,ifnull(agency_user.username,agency.contacts) as contacts,ifnull(agency_user.phone,agency.telephone) as telephone,agency.user_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id,user.username,store.store_name,agency.official,agency.product_notes')->order('agency_id desc')->select();
        foreach ($list as $k => $item) {
            $reimbursement = db('reimbursement')->join('reimbursement_relation', 'reimbursement_relation.reimbursement_id=reimbursement.id', 'left')->where('reimbursement_relation.bank_id', $item['agency_id'])->where('reimbursement.classification', 4)->where('reimbursement.user_id', $this->us['user_id'])->where('reimbursement.type', 1)->order('reimbursement.id desc')->value('reimbursement_relation.bank_id');
            if ($item['agency_id'] == $reimbursement) {
                $list[$k]['recentUse'] = 1;
            } else {
                $list[$k]['recentUse'] = 0;
            }
            
            $list[$k]['business'] = is_numeric($item['business']) ? $common->supply($item['agency_id']) : $item['business'];
            if ($item['user_id'] == 0) {
                $list[$k]['remarks'] = '公司添加';
                $list[$k]['type'] = 1;
            } else {
                $list[$k]['remarks'] = $item['store_name'] . '-店长';
                $list[$k]['type'] = 2;
            }
            unset($list[$k]['store_name'], $list[$k]['user_id']);
        }
        $recentUse = array_column($list, 'recentUse');
        $agency_id = array_column($list, 'agency_id');
        array_multisort($recentUse, SORT_DESC, $agency_id, SORT_DESC, $list);
        if ($list) {
            r_date($list, 200);
        } else {
            r_date($list, 300, "暂无关联供应商，无法选择，请联系【程伟】");
        }
        
    }
    
    /*
     * 影藏添加供应商
     */
    public function ShadowStorage() {
        r_date(1, 200);
    }
    
    /*
     * 是否有支付信息
     */
    public function PaymentInformation() {
        $parem = Request::instance()->post();
        $data  = db('agency', config('database.zong'))->where('agency_id', $parem['id'])->value('collection_number');
        $state = 1;
        if (empty($data)) {
            $state = 0;
        }
        r_date($state, 200);
    }
    
    /*
     * 合作和公司类型
     */
    public function TypeOfCooperation() {
//        $common = new \app\api\model\Common();
//        $data   = $common->supply(0);
        $data=db('detailed_category')->where('detailed_category.is_enable', 1)->field('id,title')->where('sort','<',100)->where('detailed_category.pid', 0)->order('sort asc')->select();
        r_date($data, 200);
    }
    
    /*
     * 合作和公司类型
     */
    public function SupplierType() {
        $common = new \app\api\model\Common();
        $data   = $common->SupplierType();
        r_date($data, 200);
    }
    
    /*
     * 代购主材合作公司
     */
    public function PartnerCompany_add() {
        $data = Request::instance()->post();
        if ($data['province_id']) {
            $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
        }
        if ($data['city_id']) {
            $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
        }
        if ($data['county_id']) {
            $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
        }
        $res = db('agency', config('database.zong'))->insertGetId(['agency_name' => $data['agency_name'], 'province' => $province, 'city' => $city_id, 'area' => $county, 'business' => $data['business'], 'user_id' => $this->us['user_id'], 'store_id' => $this->us['store_id'],]);
        if ($res) {
            r_date([], 200);
        }
        r_date([], 300);
    }
    
    /*
     * 代购主材列表
     */
    public function PartnerCompany_capital(Approval $approval) {
        
        $data    = Request::instance()->post();
        $common  = new \app\api\model\Common();
        $capital = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->field('projectId,capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,fen,increment,gold_suite as type,agency,acceptance')->select();
        foreach ($capital as $k => $v) {
            if ($v['fen'] == 1) {
                $product_chan = db('detailed')->where('detailed_id', $v['projectId'])->value('agency_id');
                $agency       = db('agency', config('database.zong'))->join('province p', 'agency.province=p.province_id', 'left')->join('city c', 'agency.city=c.city_id', 'left')->join('user', 'agency.user_id=user.user_id', 'left')->join('store', 'agency.store_id=store.store_id', 'left')->join('county y', 'agency.area=y.county_id', 'left')->field('agency.agency_id,agency.contacts,agency.telephone,agency.user_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id,user.username,store.store_name,agency.official,agency.product_notes')->order('agency_id desc')->whereIn('agency.agency_id', $product_chan)->where('agency.state', 1)->select();
                if ($agency) {
                    foreach ($agency as $o => $item) {
                        $agency[$o]['business'] = is_numeric($item['business']) ? array_values($approval->filter_by_value($common->supply(), 'id', $item['business']))[0]['title'] : $item['business'];
                    }
                    $capital[$k]['data'] = $agency;
                } else {
                    $capital[$k]['data'] = [];
                }
                
            } elseif ($v['fen'] == 2) {
                $product_chan = db('information')->where('id', $v['projectId'])->value('agency_id');
                $agency       = db('agency', config('database.zong'))->join('province p', 'agency.province=p.province_id', 'left')->join('city c', 'agency.city=c.city_id', 'left')->join('user', 'agency.user_id=user.user_id', 'left')->join('store', 'agency.store_id=store.store_id', 'left')->join('county y', 'agency.area=y.county_id', 'left')->field('agency.agency_id,agency.contacts,agency.telephone,agency.user_id,agency.business,agency.agency_name,p.province as province_id,c.city as city_id,y.county as county_id,user.username,store.store_name,agency.official,agency.product_notes')->order('agency_id desc')->whereIn('agency.agency_id', $product_chan)->where('agency.state', 1)->select();
                if ($agency) {
                    foreach ($agency as $j => $value) {
                        $agency[$j]['business'] = is_numeric($value['business']) ? array_values($approval->filter_by_value($common->supply(), 'id', $value['business']))[0]['title'] : $value['business'];
                    }
                    $capital[$k]['data'] = $agency;
                } else {
                    $capital[$k]['data'] = [];
                }
            } else {
                $capital[$k]['data'] = [];
            }
        }
        
        r_date($capital, 200);
        
    }
    
    /*
     * 自定义删除
     */
    public function custom_material_delect() {
        $data = Request::instance()->post();
        
        db('custom_material')->where('id', $data['id'])->update(['status' => 1]);
        
        r_date(null, 200);
        
    }
    
    /**
     * 获取材料
     */
    public function Material_translate() {
        $data = $this->model->post();
        $res  = db('stock')->field('id,company,stock_name,latest_cost,type');
        if (isset($data['title']) && $data['title'] != '') {
            $res->where(['stock_name' => ['like', "%{$data['title']}%"]]);
        }
        $res = $res->select();
        r_date($res, 200);
    }
    
    /**
     * 获取项目一级标题
     */
    public function get_my_ge() {
        $data = Request::instance()->post(['page' => 1, 'limit' => 10]);
        $res  = db('product_chan')->where(['parents_id' => 0, 'pro_types' => 1])->field('product_title,product_id')->select();
        foreach ($res as $k => $v) {
            $res[$k]['count'] = db('product_chan')->where(['parents_id' => $v['product_id'], 'pro_types' => 1])->count();
        }
        $re['tao']      = 0;
        $re['detailed'] = $res;
        $rdetailed      = db('detailed')->where(['detaileds_id' => 0, 'display' => 1, 'is_compose' => 0])->field('detailed_id,detailed_title')->page($data['page'], $data['limit'])->select();
        foreach ($rdetailed as $k => $v) {
            $rdetailed[$k]['count'] = db('detailed')->where(['detaileds_id' => $v['detailed_id']])->count();
        }
        $r['tao']      = 1;
        $r['detailed'] = $rdetailed;
        $data          = [0 => $re, 1 => $r,];
        r_date($data);
    }
    
    /**
     * 获取项目二级标题
     */
    public function get_my_er() {
        $data = Request::instance()->post(['type', 'detailed', 'page', 'limit']);
        $pr   = [];
        if ($data['type'] == 0) {
            
            $rdetailed = db('product_chan')->where(['parents_id' => $data['detailed'], 'pro_types' => 1])->join('unit un', 'un.id=product_chan.units_id', 'left')->field('product_id,product_title,parents_id,un.title,prices')->page($data['page'], $data['limit'])->select();
            foreach ($rdetailed as $k => $l) {
                $pr[$k]['projectId']    = $l['product_id'];
                $pr[$k]['projectMoney'] = $l['prices'];
                $pr[$k]['projectTitle'] = $l['product_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 0;
                $pr[$k]['agency']       = 0;
                unset($rdetailed[$k]);
            }
        } elseif ($data['type'] == 1) {
            $detailed = db('detailed')->where(['detaileds_id' => $data['detailed'], 'tao' => 0, 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed_id,detailed_title,detaileds_id,un.title,artificial,agency')->page($data['page'], $data['limit'])->select();
            foreach ($detailed as $k => $l) {
                $pr[$k]['projectId']    = $l['detailed_id'];
                $pr[$k]['projectMoney'] = $l['artificial'];
                $pr[$k]['projectTitle'] = $l['detailed_title'];
                $pr[$k]['title']        = $l['title'];
                $pr[$k]['tao']          = 1;
                $pr[$k]['agency']       = $l['agency'];
            }
        }
        r_date($pr);
    }
    
    /**
     * 获取项目二级标题
     */
    public function mandatory() {
        $data      = Request::instance()->post(['projectId']);
        $prr       = [];
        $rdetailed = db('detailed')->field('serial')->where(['detailed_id' => $data['projectId']])->find();
        if (!empty($rdetailed)) {
            $detailed_list = db('detailed_list')->field('relation')->where(['serial_id' => ['in', $rdetailed['serial']]])->find();
            if (!empty($detailed_list)) {
                $rdetailed = db('detailed')->where(['serial' => ['in', $detailed_list['relation']], 'tao' => 0, 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->field('detailed.detailed_id,detailed.detailed_title,detailed.detaileds_id,un.title,detailed.artificial,detailed.agency')->select();
                foreach ($rdetailed as $k => $l) {
                    $prr[$k]['projectId']    = $l['detailed_id'];
                    $prr[$k]['projectMoney'] = $l['artificial'];
                    $prr[$k]['projectTitle'] = $l['detailed_title'];
                    $prr[$k]['title']        = $l['title'];
                    $prr[$k]['tao']          = 1;
                    $prr[$k]['agency']       = $l['agency'];
                }
            }
        }
        r_date($prr);
    }
    
    /**
     * 基建搜索
     */
    public function despair() {
        $data = $this->model->post(['con']);
        $list = db('detailed')->field('detailed.detailed_title,detailed.detailed_id,detailed.artificial,un.title,detailed.tao,detailed.agency')->where(['detaileds_id' => ['neq', 0], 'detailed_title|serial' => ['like', "%{$data['con']}%"], 'display' => 1, 'is_compose' => 0])->join('unit un', 'un.id=detailed.un_id', 'left')->order('detailed_id desc')->select();
        $pr   = [];
        foreach ($list as $k => $l) {
            
            $pr[$k]['tao']          = 1;
            $pr[$k]['projectId']    = $l['detailed_id'];
            $pr[$k]['projectMoney'] = $l['artificial'];
            $pr[$k]['projectTitle'] = $l['detailed_title'];
            $pr[$k]['title']        = $l['title'];
            $pr[$k]['tao2']         = $l['tao'];
            $pr[$k]['agency']       = $l['agency'];
            
            unset($list[$k]);
        }
        r_date($pr);
    }
    
    
    /*
     * 修改报价清单
     */
    public function QuotationList() {
        $data = Request::instance()->post();
        db('capital')->where('capital_id', $data['capital_id'])->update(['class_b' => $data['class_b']]);
        r_date(null, 200);
    }
    
    /*
    * 修改报价清单
    */
    public function MarkCollaboration() {
        $data = Request::instance()->post();
        db('capital')->where('capital_id', $data['capital_id'])->update(['cooperation' => $data['cooperation']]);
        r_date(null, 200);
    }
    
    /*
     * 基建添加备注
     */
    public function giveRemarks() {
        $data = Request::instance()->post();
        db('capital')->where(['capital_id' => $data['capital_id']])->update(['projectRemark' => $data['projectRemark']]);
        r_date('', 200);
    }
    
    /**
     * 远程沟通删除
     */
    public function deletion() {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if (!empty($data['through_id'])) {
                $p        = db('through')->where('through_id', $data['through_id'])->field('capital_id,order_ids')->find();
                $order_id = $p['order_ids'];
                db('capital')->where(['capital_id' => ['in', $p['capital_id']]])->update(['types' => 2]);
                db('through')->where('through_id', $data['through_id'])->update(['capital_id' => '']);
                db('envelopes')->where('through_id', $data['through_id'])->update(['delete_time' => time()]);
            } else {
                $order_id = db('envelopes')->where('envelopes_id', $data['envelopes_id'])->value('ordesr_id');
                db('capital')->where(['envelopes_id' => $data['envelopes_id']])->update(['types' => 2]);
                
                db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update(['delete_time' => time()]);
            }
            $op = db('allow')->where('envelopes_id', $data['envelopes_id'])->find();
            if ($op) {
                db('allow')->where('envelopes_id', $data['envelopes_id'])->delete();
            }
            db()->commit();
            json_decode(sendOrder($order_id), true);
            r_date('', 200, '删除成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /**
     * 远程沟通列表
     */
    public function gou_list() {
        $data = $this->model->post(['page' => 1, 'limit' => 10, 'order_ids']);
        $ca   = db('envelopes')->where(['envelopes.ordesr_id' => $data['order_ids']])->join('order_aggregate', 'order_aggregate.order_id=envelopes.ordesr_id', 'left')->join('order_times', 'order_times.order_id=envelopes.ordesr_id', 'left')->field('envelopes.*,order_aggregate.agent_price,order_times.signing_time')->where('delete_time', 0)->order('envelopes_id desc')->page($data['page'], $data['limit'])->select();
        $da   = [];
        foreach ($ca as $k => $item) {
            if ($item['type'] == 1) {
                $cap = db('capital')->where(['envelopes_id' => $item['envelopes_id'], 'types' => 1, 'enable' => 1])->field('to_price,crtime,envelopes_id,fen,give,agency,products_v2_spec,products,is_product_choose')->select();
            } else {
                $cap = db('capital')->where(['envelopes_id' => $item['envelopes_id'], 'types' => 1])->field('to_price,crtime,envelopes_id,fen,give,agency,products_v2_spec,products,is_product_choose')->select();
            }
            $orderAgency = 0;
            $to_price    = 0;
            $agencyMoney    = 0;
            $MainMoney    = 0;
            foreach ($cap as $l) {
                if ($l['give'] == 0 && $l['agency'] == 1) {
                    $orderAgency = 1;
                }
                if ($l['give'] == 0 && $l['agency'] == 0) {
                    $orderAgency = 2;
                }
                if ($l['give'] == 0 && ($l['agency'] == 0 || $l['agency'] == 1)) {
                    $orderAgency = 3;
                }
                if ($l['products'] == 1 && $l['products_v2_spec'] != 0 && $l['is_product_choose'] == 1) {
                    $to_price += $l['to_price'];
                }
                if ($l['products'] == 0) {
                    $to_price += $l['to_price'];
                }
                if ($l['products'] == 1 && $l['products_v2_spec'] == 0) {
                    $to_price += $l['to_price'];
                }
                if ($l['agency'] == 1) {
                    $agencyMoney += $l['to_price'];
                }
                if ($l['agency'] == 0) {
                    $MainMoney += $l['to_price'];
                }
            }
            $approval_record    = \db('approval_record', config('database.zong'))->where('relation_id', $item['envelopes_id'])->where(function ($quer) {
                $quer->where('type', 1)->whereOr('type', 2)->whereOr('type', 3);
            })->where('status', 0)->order('approval_record.id desc')->find();
            $da[$k]['approval'] = empty($approval_record) ? 100 : $approval_record['type'];
            
            $da[$k]['project_title'] = empty($item['project_title']) ? '远程报价方案' : $item['project_title'];
            $da[$k]['th_time']       = !empty($cap[0]['crtime']) ? date('Y-m-d H:i:s', $cap[0]['crtime']) : '';
            
            if ($item['signing_time'] == 0) {
                $item['give_money']          = (string)round($item['give_money'] - $item['main_round_discount'], 2);
                $item['purchasing_discount'] = (string)round($item['purchasing_discount'] - $item['purchasing_round_discount'], 2);
                
            }
            $da[$k]['give_money']          = (string)round($item['give_money'], 2);
            $da[$k]['purchasing_expense']  = (string)round($item['purchasing_expense'], 2);
            $da[$k]['purchasing_discount'] = $item['purchasing_discount'];
            $da[$k]['amount']              = sprintf('%.3f', ($agencyMoney+$MainMoney) + ($item['expense'] + $item['purchasing_expense']) - ($da[$k]['give_money'] + $da[$k]['purchasing_discount']));
            \db('envelopes')->where('envelopes_id',$item['envelopes_id'])->update(['main_price'=>$MainMoney+$item['expense']-$da[$k]['give_money'],'agent_price'=>$agencyMoney+$item['purchasing_expense']-$da[$k]['purchasing_discount'],'total_price'=>$da[$k]['amount']]);
            $da[$k]['orderAgency']         = $orderAgency;
            $da[$k]['yc']                  = $item['through_id'];
            $da[$k]['through_id']          = $item['through_id'];
            $da[$k]['envelopes_id']        = $item['envelopes_id'];
            $da[$k]['type']                = $item['type'];
            $old                           = 0;
            if (!empty($cap) && $cap[0]['fen'] == 4) {
                $old = 1;
            }
            $da[$k]['old'] = $old;
            unset($da[$k]['capital_id']);
        }
        r_date($da, 200);
    }
    
    /**
     * 报价确认成交
     */
    public function FinalSelection(OrderModel $orderModel, Capital $capital) {
        $data = $this->model->post(['order_ids', 'yc', 'envelopes_id']);
        
        $state    = db('order')->where('order_id', $data['order_ids'])->value('state');
        $contract = db('contract')->where('orders_id', $data['order_ids'])->find();
        if ($contract['type'] == 2) {
            $main_mode_type1 = db('sign')->where('order_id', $data['order_ids'])->field('autograph,confirm')->find();
            if ($main_mode_type1['confirm'] == 3 && empty($main_mode_type1['autograph'])) {
                db('sign')->where('order_id', $data['order_ids'])->delete();
            }
            if (!empty($main_mode_type1['autograph']) && $state == 3) {
                r_date(null, 300, '合同已签字不允许切换报价');
            }
            if (!empty($main_mode_type1['autograph']) && $state > 3) {
                r_date(null, 300, '合同已签字不允许切换报价');
            }
        } else {
            if (!empty($contract['contract'])) {
                r_date(null, 300, '已上传合同图片不允许切换报价');
            }
        }
        db('sign')->where('order_id', $data['order_ids'])->delete();
        $envelopes_gantt_chart = db('envelopes_gantt_chart')->where('envelopes_id', $data['envelopes_id'])->where('delete_time', 0)->find();
        if (empty($envelopes_gantt_chart)) {
            r_date(null, 301, '因报价数据过久，需确认工期工时后才可选定');
        }
        db()->startTrans();
        try {
            $orderModel->MultiTableUpdate($data['order_ids'], 0);
            \db('envelopes')->where('envelopes_id', $data['envelopes_id'])->update(['type' => 1]);
            \db('capital')->where('envelopes_id', $data['envelopes_id'])->where('products_v2_spec', 0)->update(['enable' => 1]);
            \db('capital')->where('envelopes_id', $data['envelopes_id'])->where('is_product_choose', 1)->where('products_v2_spec', "<>", 0)->update(['enable' => 1]);
            \db('warranty_collection')->where('envelopes_id', $data['envelopes_id'])->update(['type' => 1]);
            $capitals = $capital->whetherAgency(['envelopes_id' => $data['envelopes_id'], 'types' => 1, 'enable' => 1, 'agency' => 1]);
            if ($capitals > 0) {
                $listOrderType = 1;
            } else {
                $listOrderType = 0;
            }
            $orderModel->orderAgency(['order_id' => $data['order_ids'], 'order_agency' => $listOrderType]);
            $order_setting = db('order_setting')->where('order_id', $data['order_ids'])->find();
            json_decode(sendOrder($data['order_ids']), true);
            db()->commit();
            (new NewInfrastructure)->guanlifei($order_setting, $data['order_ids'], $data['envelopes_id'], 2);
            db('envelopes_gantt_chart')->where('envelopes_id', $data['envelopes_id'])->where('delete_time', 0)->update(['update_time'=>time()]);
             openapiAddTask($data['order_ids'],4,'基建报价切换','');
            sendOrder($data['order_ids']);
            r_date('', 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
    /**
     * 远程沟通里面
     */
    public function gou2(Common $common, OrderModel $orderModel) {

        $data = $this->model->post(['remar', 'order_id', 'end_time', 'mode', 'log', 'isPending', 'afterSalesId']);
        $param                     = Request::instance()->post();
        if ($data['order_id'] == 0) {
            r_date([], 300, "参数不存在，请重试");
        }

        $list = isset($param['inspectionPhotos']) ? json_decode($param['inspectionPhotos'], true) : null;
        $detection = isset($param['detection']) ? json_decode($param['detection'], true) : null;
        $inspectionPhotos = [];
        $inspectionDetection = [];
        $resource_List = [];
        $resource_ids = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                foreach ($item['pic'] as $value) {
                    $resource_List[] = $value;
                }
                $inspectionPhotos[] = [
                    'title' => $item['title'],
                    'content'=>$item['content'],
                    'pic' => $item['pic']
                ];
            }
        }
        if (!empty($detection)) {
            foreach ($detection as $item) {
                if ($item['select'] == 1) {
                    $inspectionDetection[] = [
                        'id' => $item['id'],
                        'title' => $item['title']
                    ];
                }
            }
        }
        db()->startTrans();
        try {
            if (!empty($resource_List)) {
                $resource_ids = $common->addResourceListImg($resource_List);
            }
            $t = [
                'mode' => $data['mode'],
                'amount' => 0,
                'role' => 2,
                'role_name' => $this->us['username'],
                'admin_id' => $this->us['user_id'],
                'remar' => $data['remar'],
                'order_ids' => $data['order_id'],
                'baocun' => 0,
                'th_time' => time(),
                'end_time' => strtotime($data['end_time']),
                'rework_end_id' => $data['afterSalesId'],
                'inspection_photos' => !empty($inspectionPhotos) ? json_encode($inspectionPhotos) : '',
                'inspection_detection' => !empty($inspectionDetection) ? json_encode($inspectionDetection) : '',
                'inspection_refer' => isset($param['refer']) ? $param['refer'] : '',
                'log' => !empty($data['log']) ? serialize(json_decode($data['log'], true)) : '', //图片
                'resource_ids' => empty($resource_ids) ? '' : implode(",", $resource_ids)
            ];
            $throughId = db('through')->insertGetId($t);
            db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id'], 'already' => 1])->update(['already' => 0, 'have' => time()]);
            db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $data['order_id'], 'tai' => 1])->update(['tai' => 0]);
            db('order')->where(['order_id' => $data['order_id']])->where('state', '<', 2)->update(['undetermined' => 1, 'state' => 2, 'undetermined_time' => time()]);
            $common->MultimediaResources($data['order_id'], $this->us['user_id'], !empty($data['log']) ? json_decode($data['log'], true) : [], 2);
            if (!empty($resource_List)) {
                $common->MultimediaResources($data['order_id'], $this->us['user_id'], $resource_List, 4);
            }
            db()->commit();
            $d           = db('through')->where('order_ids', $data['order_id'])->order('through_id desc')->column('through_id');
            $s           = implode(',', $d);
            db('order_times')->where('order_id', $data['order_id'])->where('first_through_time', 0)->update(['first_through_time' => time()]);
            db('order_times')->where('order_id', $data['order_id'])->update(['late_through_time' => time()]);

            $order_times = db('order_times')->where('order_id', $data['order_id'])->find();
            db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['through_id' => $s]);
            sendOrder($data['order_id']);
            if ($order_times['first_clock_time'] != 0) {
                $common->CommissionCalculation($data['order_id'], $orderModel, 1);
            }
            //返回一个1未分享0已分享
            $through_share=0;
            if($data['mode']=="客户需求与方案报告"){
                $throughShare=db('through_share')->where(['order_id'=>$data['order_id']])->select();
                $through_share=empty($throughShare)?1:0;
            }
            r_date($through_share, 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    /**
     * 远程沟通上门基建分享
     */
     public function throughShare(){
        $request = Authority::param(['orderId']);
        $inspection_photos = db('through')->where('order_ids', $request['orderId'])->whereNotNull('inspection_photos')->order('through_id desc')->find();
         db('through_share')->insert(['through_id'=>$inspection_photos['through_id'],'order_id'=>$request['orderId'],'create_time'=>time()]);
         r_date('https://share.yiniao.co/through.html?order_id='.$request['orderId'], 200);
     }
    /**
     * 远程沟通类型
     */
    public function getRole(){
        $request = Authority::param(['orderId']);
        $clock_in   = db('clock_in')->where('order_id', $request['orderId'])->select();
        $inspection_photos = db('through')->where('order_ids', $request['orderId'])->where('mode',"客户需求与方案报告")->order('through_id desc')->select();
        if (!empty($inspection_photos)) {
            $clock_in = null;
        }
        $template   = db('user_config', config('database.zong'))->where('key', 'quotation_template')->where('status', 1)->value('value');
        $template   = json_decode($template, true);
        $list = [];
        foreach ($template as $k => $value) {
            if ($value['title'] == "全屋" || $value['title'] == "主卧" || $value['title'] == "厨房" || $value['title'] == "主卫" || $value['title'] == "生活阳台" || $value['title'] == "景观阳台") {
                $value['click'] = 0;
                $value['select'] = 0;
                $value['pic'] = null;
                $value['content'] = '';
                $list[] = $value;
            }
        }
       $detection = [['id' => 1, "title" => "湿度仪", 'select' => 0], ['id' => 2, "title" => "空鼓锤", 'select' => 0], ['id' => 3, "title" => "美纹纸", 'select' => 0], ['id' => 4, "title" => "手电筒", 'select' => 0], ['id' => 5, "title" => "激光尺", 'select' => 0]];
        $refer='';
        $remar='';
        if (!empty($inspection_photos)) {
            $clock_in = null;
            $inspectionInfo = $inspection_photos[0];
            $remar=$inspectionInfo['remar'];
            $inspection_detection = json_decode($inspectionInfo['inspection_detection'], true);
            $refer=$inspectionInfo['inspection_refer'];
            $inspection_photos = json_decode($inspectionInfo['inspection_photos'], true);
            if (!empty($inspection_photos)) {
                foreach ($list as $k => $value) {
                    foreach ($inspection_photos as $k => $val) {
                        if ($value['title'] == $val['title']) {
                            $list[$k]['select'] = 1;
                            $list[$k]['pic'] = $val['pic'];
                            $list[$k]['content'] = isset($val['content']) ? $val['content'] : '';
                        }
                    }
                }
            }

            foreach ($detection as $k => $value) {
                if ($inspection_detection) {
                    foreach ($inspection_detection as $k => $val) {
                        if ($value['id'] == $val['id']) {
                            $detection[$k]['select'] = 1;
                        }
                    }
                }
            }
            
        }
        $Customize = [
            "id" => 99,
            'click' => 1,
            "title" => "自定义"
        ];

        array_push($list, $Customize);
        r_date(['role' => [['id' => 1, "title" => "微信", 'type' => 1, 'select' => empty($clock_in) ? 1 : 0], ['id' => 2, "title" => "电话", 'type' => 1, 'select' => 0], ['id' => 3, "title" => "其它", 'type' => 1, 'select' => 0], ['id' => 4, "title" => "客户需求与方案报告", 'type' => 2, 'select' => empty($clock_in) ? 0 : 1]], 'quotation_template' => $list, 'title' => empty($clock_in) ? '' : '检测到您近期完成上门，已自动切换为上门基检跟进记录', 'detection' => $detection,'refer'=>$refer,'remar'=>$remar], 200, '新增成功');
    }
        /**
     * 远程沟通自定义类型
     */
    public function getRoleCustomize() {
        $template   = db('user_config', config('database.zong'))->where('key', 'quotation_template')->where('status', 1)->value('value');
        $template   = json_decode($template, true);
        foreach ($template as $k => $value) {
            if($value['title'] !="全屋" || $value['title'] !="主卧" || $value['title'] !="厨房"|| $value['title'] !="主卫"|| $value['title'] !="生活阳台"|| $value['title'] !="景观阳台"){
           
             $list[]=$value;
            }
            
         }
       
        r_date($list, 200, '新增成功');
    }
    /**
     * 远程沟通列表
     */
    public function get_gou() {
        $data = $this->model->post(['order_ids', 'gid']);
        $k    = db('through');
        if ($data['gid']) {
            if (strstr("店长", $data['gid'])) {
                $k->where(['role' => [['eq', 2], ['neq', 3]]]);
            } elseif (strstr("客服", $data['gid'])) {
                $k->where(['role' => [['eq', 1], ['neq', 3]]]);
            } elseif (strstr("Bi", $data['gid'])) {
                $k->where(['role' => [['eq', 4], ['neq', 3]]]);
            } else {
                $k->where(['role' => [['eq', 6], ['neq', 3]]]);
            }
        } else {
            $k->where(['role' => ['neq', 3]]);
        }
        $h = $k->where(['order_ids' => $data['order_ids']])->order('th_time desc')->select();
        foreach ($h as $k => $value) {
            if ($value['log']) {
                $h[$k]['log'] = unserialize($value['log']);
            } else {
                $h[$k]['log'] =null;
            }
            $inspection_photos=!empty($value['inspection_photos'])?json_decode($value['inspection_photos'],true):null;
            if(!empty($inspection_photos)){
               $h[$k]['photos'] =$inspection_photos;
            
            }
                
            if($value['role']==2){
                $h[$k]['part']="店长-".$value['role_name'];
            }
            if($value['role']==1){
                $h[$k]['part']="客服-".$value['role_name'];
            }
            if($value['role']==4){
                $h[$k]['part']="Bi-".$value['role_name'];

            }
            $h[$k]['refer']=$value['inspection_refer'];
            $h[$k]['detection']=!empty($value['inspection_detection'])?json_decode($value['inspection_detection'],true):null;
            $h[$k]['remar']   = !empty($value['remar']) ? $value['remar'] : '';
            $h[$k]['th_time'] = !empty($value['th_time']) ? date('Y-m-d H:i:s', $value['th_time']) : null;
            $h[$k]['end_time'] = !empty($value['end_time']) ? date('Y-m-d H:i:s', $value['end_time']) : '';
            // 处理modeType：筛选"客户需求与方案报告"的最新1条
            $h[$k]['modeType'] = 0; // 默认值
            static $foundLatest = false; // 标记是否已找到最新的一条
            if (!$foundLatest && $value['mode'] == "客户需求与方案报告") {
                $h[$k]['modeType'] = 1;
                $foundLatest = true; // 找到后标记，确保只设置最新的一条
            }
            unset($h[$k]['inspection_photos'],$h[$k]['inspection_refer'],$h[$k]['inspection_detection']);
        }
        r_date($h, 200);
    }
    
    
    /************************************************************** 订单列表**************************************************************/
    /*
     *   0"全部" 1"新订单"2"待处理"3"带上门"4"待签约"5"施工中"6"已完工"7"已收藏"8"已取消"9"退单"10"待结算"11"被投诉"
     */
    public function orderType(OrderModel $orderModel) {
        r_date($orderModel->orderType($this->us['user_id']), 200);
        
    }
    
    public function orderVagueGetList(OrderModel $orderModel) {
        $parameter = Request::instance()->get();
        r_date($orderModel->orderNewList(0, 0, $parameter['page'], $parameter['limit'], $this->us['user_id'], $parameter), 200);
    }
    
    public function orderGetList(OrderModel $orderModel) {
        $data = Authority::param(['type', 'subordinate', 'page', 'limit']);
        $list = $orderModel->orderNewList($data['type'], $data['subordinate'], $data['page'], $data['limit'], $this->us['user_id']);
        r_date($list, 200);
    }
    
    public function info(OrderModel $orderModel) {
        $data = Authority::param(['type', 'orderId']);
        if (empty($data['orderId'])) {
            r_date(null, 300, '订单id为空');
        }
         $orderInfo=db('order')->where(['order_id' => $data['orderId']])->find();
         if($orderInfo['assignor'] !=$this->us['user_id'] && $this->us['reserve']==2 && in_array($data['type'], [1, 2, 3])){
             r_date(null, 300, '没有权限查看该订单');
         }
        if ($data['type'] == 1) {
            $list = $orderModel->info($data['orderId'],$this->us);
        } elseif ($data['type'] == 2) {
            $list = $orderModel->orderAdministration($data['orderId']);
        } elseif ($data['type'] == 3) {
            $list = $orderModel->orderConstructionAdministration($data['orderId']);
        } else {
            $list          = $orderModel->reworkInfo($data['orderId'],$this->us['user_id']);
            $reworkMessage = db('message')->where(['other_id' => $data['orderId'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
            if ($reworkMessage['already'] != 0) {
                db('message')->where(['other_id' => $data['orderId']])->where('have','')->update(['already' => 0, 'have' => time()]);
            }
            
        }
        $message = db('message')->where(['order_id' => $data['orderId'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
        if ($message['already'] != 0) {
            db('message')->where(['order_id' => $data['orderId']])->where('have','')->update(['already' => 0, 'have' => time()]);
            db('remind')->where(['order_id' => $data['orderId']])->update(['tai' => 0]);
        }
        db('order_inventory_record', config('database.zong'))->where(['order_id' => $data['orderId']])->where('read_time',0)->update(['read_time' => time(),'read_user_id'=>$this->us['user_id'],'read_user_name'=>$this->us['username']]);
        db('order_times')->where(['order_id' => $data['orderId']])->where('receive_time', 0)->update(['receive_time' => time()]);
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        
        db('user_detail_view_log', config('database.zong'))->insert(['role' => 6, 'user_id' => $this->us['user_id'], 'user_name' => $this->us['username'], 'created_time' => time(), 'uri' => $_SERVER['REQUEST_URI'], 'remark' => json_encode(['client_ip' => $ip]), 'param' => json_encode(['order_id' => $data['orderId'], 'type' => $data['type']]), 'method' => $_SERVER['REQUEST_METHOD'],'order_id'=>$data['orderId'],'view_type'=>1]);
        
        r_date($list, 200);
    }
    
    public function get_order(OrderModel $orderModel) {
        $data = $this->model->post();
        
        $m = $orderModel->table('order')->alias('a')->field('a.order_id,a.rework,master_half_cost_time,a.ification,a.order_no,a.settlement_time,a.addres,a.contacts,a.telephone,a.remarks,a.lat,a.lng,a.created_time,a.state,a.quotation,a.planned,b.title,p.province,c.city,u.county,a.finish_time,if(a.hardbound=0,go.title,concat(go.title,"(精装房)")) as title,co.con_time,co.contracType,co.dep_money,co.weixin,st.dep,st.con,st.up_time,st.sta_time,be.tail,a.point,cos.type,a.undetermined,me.time as message_time,a.cleared_time,comp.time,a.point_time,a.undetermined_time,a.start_time,a.finish_time,a.tui_time,order_aggregate.main_price,order_aggregate.agent_price')->join('chanel b', 'a.channel_id=b.id', 'left')->join('order_times', 'order_times.order_id=a.order_id', 'left')->join('province p', 'a.province_id=p.province_id', 'left')->join('city c', 'a.city_id=c.city_id', 'left')->join('county u', 'a.county_id=u.county_id', 'left')->join('user us', 'a.assignor=us.user_id', 'left')->join('goods_category go', 'a.pro_id=go.id', 'left')->join('contract co', 'a.order_id=co.orders_id', 'left')->join('startup st', 'a.startup_id=st.startup_id', 'left')->join('before be', 'a.before_id=be.before_id', 'left')->join('message me', 'a.order_id=me.order_id and me.type=6 and a.assignor=me.user_id', 'left')->join('cost cos', 'a.order_id=cos.order_id', 'left')->join('complaint comp', 'a.order_id=comp.order_id', 'left')->join('order_aggregate', 'a.order_id=order_aggregate.order_id', 'left')->group('a.order_id');
        
        if (isset($data['title']) && $data['title'] != '') {
            $m->where(['a.contacts|a.telephone|a.addres|go.title' => ['like', "%{$data['title']}%"]]);
        }
        //创建时间
        if (isset($data['created_time']) && $data['created_time'] != '' && $data['created_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['created_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['order_times.dispatch_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //预约时间
        if (isset($data['planned']) && $data['planned'] != '' && $data['planned'] != 0) {
            //本日
            $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            $m->where(['a.planned' => ['between', [$beginToday, $endToday]]]);
        }
        //签约时间
        if (isset($data['con_time']) && $data['con_time'] != '' && $data['con_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['con_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['co.con_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //开工时间
        if (isset($data['start_time']) && $data['con_time'] != '' && $data['start_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['start_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.start_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //完工时间
        if (isset($data['finish_time']) && $data['con_time'] != '' && $data['finish_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['finish_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.finish_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        //完款时间
        if (isset($data['received_time']) && $data['received_time'] != '' && $data['received_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['received_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.con_time' => ['received_time', [strtotime($starttime), $enttime]]]);
        }
        //结算时间
        if (isset($data['cleared_time']) && $data['cleared_time'] != '' && $data['cleared_time'] != 0) {
            $starttime = date('Y-m-01', strtotime(date("Y-m-d", $data['cleared_time'])));
            $enttime   = strtotime(date('Y-m-d', strtotime("$starttime +1 month -1 day")));
            $m->where(['a.cleared_time' => ['between', [strtotime($starttime), $enttime]]]);
        }
        if (isset($data['state']) && $data['state'] != '' && $data['state'] != 0) {
            
            if ($data['state'] == 1) {
                $m->where(['a.state' => 1]);   //待结单
                $m->order('me.time desc');
            } elseif ($data['state'] == 2) {
                $m->where('a.through_id !=NULL or a.undetermined=1'); //带处理
                $m->where(['a.state' => ['<', 4]]);
                $m->order('a.undetermined_time desc');
            } elseif ($data['state'] == 3) {
                $m->where(['a.state' => 2]);  //带上门
                $m->order('a.planned desc');
            } elseif ($data['state'] == 4) {
                $m->where(['a.state' => 3]);  //待签约
                $m->order('a.order_id desc');
            } elseif ($data['state'] == 5) {
                $m->where(['a.state' => ['between', [4, 5]]]);   //施工中
                $m->order('co.con_time desc');
            } elseif ($data['state'] == 6) {
                $m->where(['a.state' => ['between', [6, 7]]]); //已完工
                $m->whereNull('a.cleared_time'); //已完工
                $m->whereNull('a.received_time'); //已完工
                $m->order('a.finish_time desc');
            } elseif ($data['state'] == 7) {
                
                $m->where(['a.point' => 2]);//已收藏
                $m->order('a.point_time desc');
            } elseif ($data['state'] == 8) {
                $m->where(['a.state' => 8]);  // 已取消
                $m->order('a.tui_time desc');
            } elseif ($data['state'] == 9) {
                $m->where(['a.state' => 9]);//已退单
                $m->order('a.tui_time desc');
            } elseif ($data['state'] == 10) {
                $m->where(['a.state' => ['between', [6, 7]]]); //已完工
//                $m->whereNull('a.cleared_time'); //已完工
                $m->where('if(order_aggregate.main_price=0,a.settlement_time IS NULL,a.cleared_time IS NULL)');
                $m->whereNotNull('a.received_time'); //已完工
                $m->order('a.received_time desc');
            } elseif ($data['state'] == 11) {
                $order_id = \db('complaint')->column('order_id');
                $m->whereIn('a.order_id', $order_id);//投诉订单
                $m->order('comp.time desc');
            } elseif ($data['state'] == 12) {
                $m->whereNotNull('a.cleared_time');//已结算
                $m->order('a.cleared_time desc');//已结算
            } elseif ($data['state'] == 13) {
                $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $endToday   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                $order_id   = db('through')->where('role', 2)->where('admin_id', $this->us['user_id'])->whereBetween('end_time', [$beginToday, $endToday])->column('order_ids');
                $m->whereIn('a.order_id', $order_id);
            }
            //排除掉待处理订单
            if ($data['state'] != 7 && $data['state'] != 8 && $data['state'] != 9 && $data['state'] != 13) {
                if ($data['state'] != 2) {
                    $m->where(['a.undetermined' => 0]);
                } else {
                    $m->where(['a.undetermined' => 1]);
                }
            }
            
        } else {
            $m->where(['a.state' => ['neq', 10]]);
            $m->order('a.order_id desc');//已结算
        }
        if (isset($data['user_id']) && $data['user_id'] != 0) {
            $m->where(['a.assignor' => $data['user_id']]);
        } else {
            $m->where(['a.assignor' => $this->us['user_id']]);
        }
        if (isset($data['acceptance_time'])) {
            $m->whereNotNull('a.acceptance_time');
            $m->whereNull('a.settlement_time');
        }
        if (isset($data['settlement_time'])) {
            $m->whereNotNull('a.settlement_time');
        }
        if (isset($data['order_agency'])) {
            $m->where('a.order_agency', 1);
            $m->where('a.state', '>', 3);
            $m->whereNull('a.settlement_time');
            $m->whereNull('a.acceptance_time');
        }
        $list = $m->page($data['page'], $data['limit'])->select();
        foreach ($list as $k => $key) {
            $order_rework                  = db('order_rework')->where(['order_id' => $key['order_id']])->field('customer,reason as rewordDes,master_id')->order('id desc')->find();
            $list[$k]['customer']          = !empty($order_rework['customer']) ? $order_rework['customer'] : null;
            $list[$k]['rewordDes']         = !empty($order_rework['rewordDes']) ? $order_rework['rewordDes'] : null;
            $list[$k]['master_id']         = !empty($order_rework['master_id']) ? $order_rework['master_id'] : null;
            $list[$k]['con_time']          = !empty($key['con_time']) ? date('Y-m-d H:i:s', $key['con_time']) : '';
            $list[$k]['up_time']           = !empty($key['up_time']) ? date('Y-m-d H:i:s', $key['up_time']) : '';
            $list[$k]['start_time']        = !empty($key['start_time']) ? date('Y-m-d H:i:s', $key['start_time']) : '';
            $list[$k]['finish_time']       = !empty($key['finish_time']) ? date('Y-m-d H:i:s', $key['finish_time']) : '';
            $list[$k]['sta_time']          = !empty($key['sta_time']) ? date('Y-m-d H:i:s', $key['sta_time']) : '';
            $list[$k]['created_time']      = !empty($key['created_time']) ? date('Y-m-d H:i', $key['created_time']) : '';
            $list[$k]['planned']           = !empty($key['planned']) ? date('Y-m-d H:i:s', $key['planned']) : '';
            $list[$k]['tui_time']          = !empty($key['tui_time']) ? date('Y-m-d H:i:s', $key['tui_time']) : '';
            $list[$k]['time']              = !empty($key['time']) ? date('Y-m-d H:i:s', $key['time']) : '';
            $list[$k]['cleared_time']      = !empty($key['cleared_time']) ? date('Y-m-d H:i:s', $key['cleared_time']) : '';
            $list[$k]['point_time']        = !empty($key['point_time']) ? date('Y-m-d H:i:s', $key['point_time']) : '';
            $list[$k]['undetermined_time'] = !empty($key['undetermined_time']) ? date('Y-m-d H:i:s', $key['undetermined_time']) : '';
            $crtime                        = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1])->order('capital_id desc')->value('crtime');
            $list[$k]['crtime']            = !empty($crtime) ? date('Y-m-d H:i:s', $crtime) : '';
            $offer                         = $orderModel::offer($key['order_id']);
            $list[$k]['amount']            = $offer['amount'];
            if (empty($offer['amount'])) {
                $list[$k]['amount'] = sprintf("%.2f", $offer['agency']);
            }
            $list[$k]['payment'] = 1;
            if ($offer['yu'] < 0) {
                $list[$k]['payment'] = 2;
            }
            $list[$k]['yu']           = $offer['yu'];
            $list[$k]['yc']           = $offer['yc'];
            $list[$k]['gong']         = $offer['gong'];
            $list[$k]['message_time'] = put_time($key['message_time']);
            $list[$k]['agency']       = db('capital')->where(['ordesr_id' => $key['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();//代购主材;
            if (!empty($key['cleared_time']) && empty($list[$k]['agency'])) {
                $list[$k]['settlement'] = 1;
            } elseif (!empty($key['cleared_time']) && !empty($list[$k]['agency']) && !empty($list[$k]['settlement_time'])) {
                $list[$k]['settlement'] = 1;
            } elseif (!empty($key['cleared_time']) && !empty($list[$k]['agency']) && empty($list[$k]['settlement_time'])) {
                $list[$k]['settlement'] = 0;
            } else {
                $list[$k]['settlement'] = 0;
            }
            
            if (isset($data['state']) && $data['state'] == 11) {
                $list[$k]['complaint'] = 11;
            } else {
                $list[$k]['complaint'] = 0;
            }
            $i                    = db('through')->where(['order_ids' => $key['order_id'], 'role' => 2])->field('end_time,th_time')->order('through_id desc')->find();
            $list[$k]['end_time'] = !empty($i['end_time']) ? date('Y-m-d H:i:s', $i['end_time']) : '';
            $list[$k]['th_time']  = !empty($i['th_time']) ? date('Y-m-d H:i:s', $i['th_time']) : '';
            $list[$k]['remind']   = db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $key['order_id']])->value('tai');
        }
        
        if (isset($data['Test']) && $data['Test'] == 1) {
            res_date(array_merge($list));
        } else {
            r_date(array_merge($list));
        }
        
    }
    
    /*
     * 工作台中待沟通红点小时
     */
    public function workProcessing() {
        $data = $this->model->post();
        db('through')->where('order_ids', $data['order_id'])->update(['handle' => time()]);
        r_date(null, 200);
    }
    
    
    /*
     * 待处理
     */
    public function PendingDisposal() {
        $data    = $this->model->post(['order_id']);
        $message = db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->order('id desc')->find();
        if ($message['already'] != 0) {
            db('message')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['already' => 0, 'have' => time()]);
        }
        $res = db('remind')->where(['order_id' => $data['order_id'], 'admin_id' => $this->us['user_id']])->value('tai');
        if ($res != 0) {
            db('remind')->where(['admin_id' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['tai' => 0]);
        }
        db('order')->where(['order_id' => $data['order_id']])->where('state', '<', 4)->update(['undetermined' => 1, 'state' => 2, 'undetermined_time' => time()]);
        $orderSMS = json_decode(sendOrder($data['order_id']), true);
        (new PollingModel())->automatic($data['order_id'], 2);
        if ($orderSMS['code'] != 200) {
            r_date([], 300, '操作失败');
        }
        r_date([], 200);
    }
    
    /**
     * 报价信息
     */
    public function get_jia() {
        $data = $this->model->post(['order_id']);
        $s    = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->select();
        
        r_date($s, 200);
    }
    
    /*********************************************************************** * 重点标签***************************************************************************  */
    
    
    /**
     * 获取标签
     */
    public function get_label() {
        $res = db('label')->where(['user_id' => ['eq', 0]])->select();
        $rss = db('label')->where('user_id', $this->us['user_id'])->select();
        if ($rss) {
            $o = array_merge($res, $rss);
        } else {
            $o = $res;
        }
        
        r_date(array_values($o));
    }
    
    /**
     * 标记
     */
    public function point() {
        $data = Authority::param(['type', 'order_id']);
        $b    = db('order')->where('order_id', $data['order_id'])->update(['point' => $data['type'], 'point_time' => time()]);
        r_date([], 200);
    }
    
    /*
     * 用户端显示报价
     */
    public function allow() {
        $data = $this->model->post(['order_id', 'envelopes_id', 'yc']);
        
        if ($data['yc'] == 1) {
            $yc = 2;
        } else {
            $yc = 1;
        }
        $allow = db('allow')->where(['order_id' => $data['order_id'], 'envelopes_id' => $data['envelopes_id'], 'yc' => $yc])->find();
        
        if (empty($allow)) {
            $cop = \db('capital')->where(['ordesr_id' => $data['order_id'], 'envelopes_id' => $data['envelopes_id']])->column('capital_id');
            db('allow')->insertGetId(['order_id' => $data['order_id'], 'capital_id' => implode(',', $cop), 'envelopes_id' => $data['envelopes_id'], 'yc' => $yc, 'time' => time(),]);
        }
        r_date([], 200);
    }
    /*
     * 用户查看报价数据
     */
    public function viewQuotationData(){
        $allow     = db('allow')
            ->join('order', 'order.order_id=allow.order_id')
            ->join('order_info', 'order_info.order_id=allow.order_id')
            ->field('order_info.pro_id_title as title,order.contacts,order.telephone,order.addres,order.attributions,allow.id,allow.time,order.order_id as orderId')
            ->where(['order.assignor' => $this->us['user_id'],'order.state'=>['<','4']])
            ->order('allow.id desc')
            ->select();
           $envelopes_view=\db('envelopes_view', config('database.zong'))->whereIn('allow_id',array_column($allow,'id'))->select();
           foreach ($allow as $k=>$item) {
               $allowList=[];
               foreach ($envelopes_view as $value) {
                   if ($item['id'] == $value['allow_id']) {
                       $allowList[]=$value;
                   }
               }
               $allow[$k]['sharingDays']=ceil((time()-$item['time'])/86400);
               $allow[$k]['count']=empty($allowList)?'':count($allowList).'次';
               $allow[$k]['newTime']=empty($allowList)?'用户查看时间:暂未查看':'最新时间'.date('Y-m-d H:i:s',max(array_column($allowList,'create_time')));
               $allow[$k]['timing']=empty($allowList)?0:ceil(array_sum(array_column($allowList,'user_browse_duration'))/60);
               unset($allow[$k]['time']);
           }
        r_date(['list'=>$allow,'count'=>count($allow)], 200);
    }
    /*
 * 用户查看报价数据详情
 */
    public function viewQuotationInfo(){
        $data            = Authority::param(['orderId']);
        $allow     = db('allow')
            ->join('envelopes', 'envelopes.envelopes_id=allow.envelopes_id')
            ->field('envelopes.project_title as title,allow.id,allow.time,envelopes.envelopes_id')
            ->where(['allow.order_id'=>$data['orderId']])
            ->select();
        
        $envelopes_view=\db('envelopes_view', config('database.zong'))
            ->join('customers', 'customers.customers_id=envelopes_view.customers_id')
            ->field('envelopes_view.allow_id,concat("共计",envelopes_view.user_browse_duration,"秒") as second,FROM_UNIXTIME(envelopes_view.create_time,"%Y-%m-%d %H:%i:%s") as createTime,concat("【尾号",SUBSTRING(customers.mobile, -4),"】") as mobile')
            ->whereIn('allow_id',array_column($allow,'id'))->order('envelopes_view.create_time desc')->select();
        foreach ($allow as $k=>$item) {
            $allowList=[];
            foreach ($envelopes_view as $value) {
                if ($item['id'] == $value['allow_id']) {
                    $allowList[]=$value;
                }
            }
            $envelopes = db('capital')->field('
                capital.capital_id as capitalId,
                if(capital.agency=0,capital.to_price,0) as main_price,
                 if(capital.agency=1,capital.to_price,0) as agent_price,
                envelopes.envelopes_id,
               envelopes.give_money,
                envelopes.expense,
                envelopes.gong,
                envelopes.purchasing_discount,
                envelopes.purchasing_expense,
                envelopes.main_round_discount,
                envelopes.purchasing_round_discount,
                envelopes.created_time')->join('envelopes', 'envelopes.envelopes_id=capital.envelopes_id')->whereRaw('if(envelopes.type=1,capital.types=1 and capital.enable=1,capital.types=1)')->where(function ($quer) {
                $quer->where(function ($querss) {
                    $querss->where(['products' => 1, 'unique_status' => 1]);
                })->whereOr(function ($querss) {
                    $querss->where(['products' => 1, 'unique_status' => 0, 'is_product_choose' => 1]);
                })->whereOr(function ($querss) {
                    $querss->where(['products' => 0]);
                });
            })->where('envelopes.envelopes_id', $item['envelopes_id'])->where('envelopes.ordesr_id', $data['orderId'])->group('capital.capital_id')->select();
           
            $money    = array_sum(array_column($envelopes, 'main_price')) + array_sum(array_column($envelopes, 'agent_price')) - $envelopes[0]['give_money'] - $envelopes[0]['purchasing_discount'] + $envelopes[0]['expense'] + $envelopes[0]['purchasing_expense'];
            $allow[$k]['time']=date('Y-m-d H:i:s',$item['time']);
            $allow[$k]['money']=$money;
            $allow[$k]['list']=empty($allowList)?null:$allowList;
           
        }
        r_date($allow, 200);
    }
    
    
    /*
    * 用户端显示报价
    */
    public function all() {
        $data = $this->model->post(['envelopes_id', 'order_id', 'yc']);
        if ($data['yc'] == 0) {
            $yc = 1;
        } else {
            $yc = 2;
        }
        $allow     = db('allow')->where(['order_id' => $data['order_id'], 'envelopes_id' => $data['envelopes_id']])->find();
        $envelopes = db('capital')->field('
                capital.capital_id as capitalId,
                if(capital.agency=0,capital.to_price,0) as main_price,
                 if(capital.agency=1,capital.to_price,0) as agent_price,
                envelopes.envelopes_id,
               envelopes.give_money,
                envelopes.expense,
                envelopes.gong,
                envelopes.purchasing_discount,
                envelopes.purchasing_expense,
                envelopes.main_round_discount,
                envelopes.purchasing_round_discount,
                envelopes.created_time')->join('envelopes', 'envelopes.envelopes_id=capital.envelopes_id')->whereRaw('if(envelopes.type=1,capital.types=1 and capital.enable=1,capital.types=1)')->where(function ($quer) {
            $quer->where(function ($querss) {
                $querss->where(['products' => 1, 'unique_status' => 1]);
            })->whereOr(function ($querss) {
                $querss->where(['products' => 1, 'unique_status' => 0, 'is_product_choose' => 1]);
            })->whereOr(function ($querss) {
                $querss->where(['products' => 0]);
            });
        })->where('envelopes.envelopes_id', $data['envelopes_id'])->where('envelopes.ordesr_id', $data['order_id'])->group('capital.capital_id')->select();
        if (empty($envelopes)) {
            r_date(null, 300, '请传递正确的参数');
        }
        if (empty($allow)) {
            db('allow')->insertGetId(['order_id' => $data['order_id'], 'capital_id' => implode(',', array_column($envelopes, 'capitalId')), 'envelopes_id' => $data['envelopes_id'], 'yc' => $yc, 'time' => time(),]);
        } else {
            db('allow')->where('id', $allow['id'])->update(['capital_id' => implode(',', array_column($envelopes, 'capitalId'))]);
            
        }
        $money    = array_sum(array_column($envelopes, 'main_price')) + array_sum(array_column($envelopes, 'agent_price')) - $envelopes[0]['give_money'] - $envelopes[0]['purchasing_discount'] + $envelopes[0]['expense'] + $envelopes[0]['purchasing_expense'];
        $con_time = db('contract')->where('orders_id', $data['order_id'])->value('con_time');
        if (empty($con_time)) {
            $money = $money + $envelopes[0]['purchasing_round_discount'] + $envelopes[0]['main_round_discount'];
        }
        $time     = time();
        $Lasttime = strtotime(date('Y-m-d 12:30:00', strtotime('+1 day')));
        $more     = $Lasttime - $time;
//        $Client   = new Client();
//        $ccPush   = new ccPush($more, 'delay_template_notice', 'delay_topic', 'delay.template_notice');
//        $list = ['orderId' => $data['order_id'], 'context' => "预计工期" . $envelopes[0]['gong'] . " 天", 'price' => $money, "time" => date('Y-m-d H:i:s', $time)];
//        $Client->index(json_encode($list), 'template_success', 'template.success', 'exchange_topic');
//        $ccPush->push(json_encode($list), 'delay_template_notice', 'delay_topic', 'delay.template_notice');
        r_date([], 200);
    }
    
    /*** ************************************************************确认时间***************************************************
     **************************************************************** types等于1是需要改变订单状态* types等于2是只需修改上门时间 */
    public function get_planned(PollingModel $pollingModel) {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $us = db('order')->where('order_id', $data['order_id'])->field('telephone,planned,undetermined,tui_jian,tui_role,pro_id,assignor,state,building,unit,room')->find();
            if ($us['state'] > 2) {
                r_date(null, 300, '状态错误,无法修改预约上门时间');
            }
            if ($data['types'] == 1 || $data['types'] == 2) {
                if ($us['undetermined'] == 1) {
                    orderModel::update(['undetermined' => 0], ['order_id' => $data['order_id']]);
                }
                $building    = $us['building'];
                $unit        = $us['unit'];
                $room        = $us['room'];
                $building_no = 0;
                $unit_no     = 0;
                if (isset($data['building'])) {
                    $building = $data['building'];
                    if ($data['building'] == 'noBuildingNumber') {
                        $building_no = 1;
                        $building    = '';
                    }
                }
                if (isset($data['unit'])) {
                    $unit = $data['unit'];
                    if ($data['unit'] == 'noBuildingNumber') {
                        $unit_no = 1;
                        $unit    = '';
                    }
                    
                }
                if (isset($data['room'])) {
                    $room = $data['room'];
                }
                $orderList = ['planned' => strtotime($data['planned']), 'planned_update_time' => time(), 'update_time' => time(), 'appointment' => time(), 'building' => $building, 'unit' => $unit, 'room' => $room];
                if ($data['types'] == 1) {
                    $orderList['state'] = 2;
                }
                Db::connect(config('database.db2'))->execute('INSERT INTO `order_extend_info`(`building_no`, `unit_no`,  `order_id`) VALUES (' . $building_no . ',' . $unit_no . ',' . $data["order_id"] . ')  ON DUPLICATE KEY UPDATE `building_no`= ' . $building_no . ',`unit_no`= ' . $unit_no);
                db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update($orderList);
                db('cc_task', config('database.cc'))->where('order_id', $data['order_id'])->where('type', 1)->where('status', 0)->update(['writetime' => strtotime($data['planned']), 'admin_id' => 0, 'status' => 1]);
                $user = $this->us['username'];
                if ($data['types'] == 1) {
                    if (preg_match("/^1[345678]{1}\d{9}$/", $us['telephone'])) {
                        $WxService = new WxService();
                        $post_data = ['path' => 'pages/appointment/appointment', //                        'query' => "id={$us['assignor']}",
                            'env_version' => 'release', 'expire_type' => 1, 'expire_interval' => 179];
                        $url       = $WxService->getWxUrlLink($post_data);
                        $url       = explode("?", $url)[1];
                        sendMsg($us['telephone'], 273080157, [$user, $data['planned'], $url]);
//                    sendMsg($us['telephone'], 8612, [$user, $data['planned']]);
                    
                    }
                    if ($data['nodian'] != 1) {
                        remind($data['order_id'], 2);
                    }
                }
                $read = \db('workbench_read')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->find();
                if ($read) {
                    \db('workbench_read')->where(['order_id' => $data['order_id'], 'user_id' => $this->us['user_id']])->update(['have' => time(), 'already' => 0]);
                }
                \db('workbench_read')->insert(['type' => 1, 'order_id' => $data['order_id'], 'time' => strtotime($data['planned']), 'user_id' => $this->us['user_id']]);
                $y = ['planneds' => '', 'planned' => [], 'building' => $us['building'], 'unit' => $us['unit'], 'room' => $us['room']];
            } elseif ($data['types'] == 3) {
                $y                 = db('planned')->where(['order_id' => $data['order_id']])->field('planned')->order('id desc')->select();
                $order_extend_info = Db::connect(config('database.db2'))->table('order_extend_info')->where('order_id', $data['order_id'])->find();
                if ($order_extend_info['building_no'] == 1) {
                    $us['building'] = 'noBuildingNumber';
                }
                if ($order_extend_info['unit_no'] == 1) {
                    $us['unit'] = 'noBuildingNumber';
                }
                if (!empty($y)) {
                    foreach ($y as $k => $value) {
                        $y[$k] = !empty($value['planned']) ? date("Y-m-d H:i", $value['planned']) : '';
                    }
                    $y = ['planneds' => !empty($us['planned']) ? date("Y-m-d H:i", $us['planned']) : '', 'planned' => !empty($y) ? $y : [], 'building' => $us['building'], 'unit' => $us['unit'], 'room' => $us['room']];
                } else {
                    $y = ['planneds' => !empty($us['planned']) ? date("Y-m-d H:i", $us['planned']) : '', 'planned' => [], 'building' => $us['building'], 'unit' => $us['unit'], 'room' => $us['room']];
                }
            }
            if ($y) {
                db()->commit();
                if ($data['types'] == 1) {
                    $similarOrders = similarOrders($data['order_id'], 1);
                  }
                  if($data['types'] !=3 ){
                      openapiAddTask($data['order_id'],2,'上门预约时间','');
                  }
                
                sendOrder($data['order_id']);
                r_date($y, 200);
            }
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 补充地址提示撞单
     */
    public function BuildingNumberAdd() {
        $data = Authority::param(['building', 'unit', 'room', 'orderId']);
        if (empty($data['building']) || empty($data['unit']) || empty($data['room'])) {
            r_date(null, 300, '请填写楼栋门牌号信息');
        }
        $building_no = 0;
        $unit_no     = 0;
        $building    = $data['building'];
        if ($data['building'] == 'noBuildingNumber') {
            $building_no = 1;
            $building    = '';
        }
        $unit = $data['unit'];
        if ($data['unit'] == 'noBuildingNumber') {
            $unit_no = 1;
            $unit    = '';
        }
        $room = $data['room'];
        db('order')->where(['order_id' => $data['orderId']])->update(['building' => $building, 'unit' => $unit, 'room' => $room]);
        $res           = Db::connect(config('database.db2'))->execute('INSERT INTO `order_extend_info`(`building_no`, `unit_no`,  `order_id`) VALUES (' . $building_no . ',' . $unit_no . ',' . $data["orderId"] . ')  ON DUPLICATE KEY UPDATE `building_no`= ' . $building_no . ',`unit_no`= ' . $unit_no);
        $similarOrders = similarOrders($data['orderId'], 1);
        $msg           = '';
        if ($similarOrders['code'] == 0 && empty($similarOrders['order_nos'])) {
            $msg = '当前订单有撞单风险，请等待售前处理';
            r_date(null, 300, $msg);
        }
        r_date(null, 200, $msg);
    }
    
    public function phone(TelephoneNotification $telephoneNotification) {
        $data  = Authority::param(['orderId','type']);
        $order = \db('order')->where('order_id', $data['orderId'])->join('user', 'user.user_id=order.assignor', 'left')->field('order.telephone,user.mobile,user.bind_ax_mobile,user.bind_ax_mobile_gid')->find();
        \db('order_phone_statistics', config('database.zong'))->insert(['order_id'=>$data['orderId'],'user_mobile' => $order['mobile'], 'customers_mobile' => $order['telephone'],'created_time'=>time(),'type'=>$data['type'],'role'=>6]);
        if (preg_match('/^\d{11}$/', $order['telephone']) != 1) {
            r_date(['telX' => $order['telephone']], 200);
        }
        if (empty($order['bind_ax_mobile'])) {
            r_date(['telX' => $order['telephone']], 200);
        }
        $order_times = \db('order_times')->where('order_id', $data['orderId'])->find();
        
        $tel['mobile']         = $order['mobile'];
        $tel['telephone']      = $order['telephone'];
        $tel['bind_ax_mobile'] = $order['bind_ax_mobile'];
        $tel['orderId']        = $data['orderId'];
        $tel['date']           = date('Y-m-d H:i:s', strtotime('+1 year'));
        if (empty($order['bind_ax_mobile_gid'])) {
            $l = $telephoneNotification::CreateAxgGroup(['username' => $this->us['username'], 'user_id' => $this->us['user_id']]);
            \db('user')->where('user_id', $this->us['user_id'])->update(['bind_ax_mobile_gid' => $l]);
            $tel['groupId'] = $l;
        } else {
            $tel['groupId'] = $order['bind_ax_mobile_gid'];
        }
        $order_audio = \db('order_audio', config('database.zong'))->where(['order_id' => $data['orderId'], 'user_mobile' => $tel['mobile'], 'customers_mobile' => $tel['telephone']])->find();
        if (empty($order_audio)) {
            $tel['outId'] = 'my' . order_sn();
        } else {
            $tel['outId'] = $order_audio['only_id'];
        }
        if ($telephoneNotification::addNumbers($tel)) {
            $l = $telephoneNotification::main($tel);
            if ($l['code'] == 200) {
                $tel['subsId'] = $l['data']['subsId'];
                $Update        = $telephoneNotification::UpdateSubscription($tel);
                if (empty($order_audio)) {
                    $id = db('order_audio', config('database.zong'))->insertGetId(['order_id' => $data['orderId'], 'user_mobile' => $tel['mobile'], 'customers_mobile' => $tel['telephone'], 'requestId' => 0, 'bind_end' => strtotime($tel['date']), 'telX' => $l['data']['secretNo'], 'subId' => $l['data']['subsId'], 'created_time' => time(), 'only_id' => $tel['outId']]);
                }
                if ($order && $order_times['first_call_time'] == 0) {
                    $order = \db('order_times')->where('order_id', $data['orderId'])->update(['first_call_time' => time()]);
                }
                r_date(['telX' => $l['data']['secretNo']], 200);
            } else {
                r_date(['telX' => $tel['telephone']], 200);
            }
        } else {
            r_date(['telX' => $tel['telephone']], 200);
        }
        
    }
    
    /*
     * 上门打卡
     */
    public function ClockIn(OrderModel $orderModel, Common $common) {
        $data = $this->model->post(['order_id', 'lat', 'lng', 'picture', 'address','uuid']);
        if(!empty($data['picture'])){
            if($this->us['work_clothes']==1){
                $detectUrl=detectUrl($data['picture']);
                $detectUrl=json_decode($detectUrl,true);
                if($detectUrl['status']=='success' &&(empty($detectUrl['detections']) || $detectUrl['detections'][0]['confidence'] <50))  {
                    r_date(null, 300,'未检测到工服，无法打卡，若已穿戴，请调整角度露出工服益鸟logo'); 
                }
            }
           
        }
        $clock_in    = \db('clock_in')->where('order_id', $data['order_id'])->find();
        $punch_clock = time();
        
        db('clock_in')->insertGetId(['order_id' => $data['order_id'], 'lat' => $data['lat'], 'lng' => $data['lng'], 'address' => $data['address'], 'picture' => $data['picture'], 'punch_clock' => $punch_clock,'device_id'=>$data['uuid']]);
        $order = \db('order')->where('order_id', $data['order_id'])->value('state');
        if ($order < 4) {
            db('order')->where('order_id', $data['order_id'])->update(['state' => 3, 'undetermined' => 0]);
        }
        
        $order_times = db('order_times')->where('order_id', $data['order_id'])->find();
        if (!empty($order_times)) {
            if (empty($order_times['first_clock_time'])) {
                db('order_times')->where('order_id', $data['order_id'])->update(['first_clock_time' => time(), 'late_clock_time' => time()]);
                db('cc_task_delay',config('database.zong'))->insert(['tim'=>$punch_clock+3*60*60,'params'=>$data['order_id'],'types'=>2,'status'=>0]);
            } else {
                db('order_times')->where('order_id', $data['order_id'])->update(['late_clock_time' => time()]);
            }
        }
        if (empty($clock_in)) {
            $common->CommissionCalculation($data['order_id'], $orderModel, 1,3);
           }
        json_decode(sendOrder($data['order_id']), true);
        $addShareRewardByOrder = addShareRewardByOrder($data['order_id']);
        openapiAddTask($data['order_id'],3,'定位打卡','');
        db('log', config('database.zong'))->insertGetId(['content' => $addShareRewardByOrder, 'ord_id' => $data['order_id'], 'type' => 19, 'msg' => '小程序活动补卡', 'admin_id' => $this->us['user_id'], 'created_at' => time()]);
        $common->MultimediaResources($data['order_id'], $this->us['user_id'], $data['picture'], 3);
        r_date(null, 200);
    }
    
    /*
     * 订单取消原因
     */
    public function reasonForCancellation() {
        $list_process = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'cancellation')->where('statusss', 1)->find();
        $list_process = json_decode($list_process['valuess'], true);
        r_date($list_process, 200);
    }
    
    /**
     * 取消订单/退单子
     */
    public function get_reason(Common $commons) {
        $data           = $this->model->post(['order_id', 'reason', 'tui_moey']);
        $state          = db('order')->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'left')->where(['order.order_id' => $data['order_id']])->field('order.state,order_aggregate.payment_price')->find();
        $reason         = json_decode($data['reason'], true);
        $OriginalReason = '';
        $cancellation   = [];
        foreach ($reason as $item) {
            if (isset($item['selected']) && $item['selected'] == true) {
                array_push($cancellation, ['order_id' => $data['order_id'], 'pid' => 1, 'cancellation_id' => $item['id'], 'cancellation_title' => $item['title'], 'created_time' => time(),]);
                $OriginalReason .= $item['title'] . '-';
                foreach ($item['data'] as $list) {
                    if (isset($list['selected']) && $list['selected'] == true) {
                        array_push($cancellation, ['order_id' => $data['order_id'], 'pid' => 2, 'cancellation_id' => $list['id'], 'cancellation_title' => $list['title'], 'created_time' => time(),]);
                        array_push($cancellation, ['order_id' => $data['order_id'], 'pid' => 3, 'cancellation_id' => 0, 'cancellation_title' => $list['data']['reason'], 'created_time' => time(),]);
                        $OriginalReason .= $list['title'] . '-' . $list['data']['reason'] . ',';
                        
                    }
                }
                
            }
        }
        if ($state['state'] < 4) {
            $list['through'] = db('through')->where(['order_ids' => $data['order_id']])->where('mode',"客户需求与方案报告")->limit(1)->count() > 0 ? 1 : 0;
            $list['clockIn']=Db::connect(config('database.db2'))->table('clock_in')->where('order_id', $data['order_id'])  ->limit(1) ->count() > 0 ? 1 : 0;
            $order_time = Db::connect(config('database.db2'))->table('order_times')->where('order_id', $data['order_id'])->find();
            if ($state['state'] < 4 &&  $list['through'] == 0 && $list['clockIn'] == 1  &&  ($order_time['dispatch_time']>1763654400 || $order_time['turn_time']>1763654400) && $this->us['through_inspection']==1) {
                r_date(null,300,"已上门订单，若需要取消订单，需要完成基检报告未完成时，无法取消");
            }
            Db::name('order_rec')->insert(['order_id' => $data['order_id'], 'cxl_state' => $state['state'], 'create_time' => time()], true);
            $tui_time = time();
            if (empty($OriginalReason)) {
                r_date(null, 300, '请输入原因');
            }
            $Common                = $commons::order_for_payment($data['order_id']);
            $da['material']        = 0;
            $da['agency_material'] = 0;
        
            if ($Common[0] != 0 ||$Common[1] != 0) {
                r_date(null, 300, '有收款或收款在审核中，请先操作退款或联系财务驳回收款');
            }
            $da = db('order')->where(['assignor' => $this->us['user_id'], 'order_id' => $data['order_id']])->update(['state' => 8, 'reason' => $OriginalReason, 'tui_time' => $tui_time, 'update_time' => $tui_time, 'port' => 3, 'undetermined' => 0]);
            db('order_cancellation')->insertAll($cancellation);
            openapiAddTask($data['order_id'],8,'店长取消','');
        } else {
            $total_price    = db('material_usage')->where(['status' => ['<>', 2], 'order_id' => $data['order_id']])->sum('total_price');
            $_reimbursement = db('reimbursement')->where(['order_id' => $data['order_id'], 'status' => ['<>', 2]])->count();
            if ($total_price != 0 || $_reimbursement != 0) {
                r_date(null, 300, '有材料领用，或报销不能退单请走结算');
            }
            $tui_time = time();
            if (empty($data['reason'])) {
                r_date(null, 300, '请输入原因');
            }
            if ($state['payment_price'] != 0) {
                r_date(null, 300, '输入退款金额');
            }
            $da = db('order')->where(['order_id' => $data['order_id'], 'assignor' => $this->us['user_id']])->update(['state' => 9, 'reason' => $OriginalReason, 'tui_moey' => $data['tui_moey'], 'tui_state' => 1, 'tui_time' => $tui_time, 'update_time' => $tui_time, 'port' => 3]);
            openapiAddTask($data['order_id'],8,'店长退单','');
        }
         if ($da) {
            sendOrder($data['order_id']);
            r_date([], 200);
        }
        r_date([], 300);
    }
    
    
    /*
     * 代购主材验收
     */
    public function CheckBefore() {
        $data = $this->model->post(['capital_id']);
        db()->startTrans();
        try {
            $prove = json_decode($data['prove'], true);
            if (empty($prove)) {
                throw new Exception('请填写凭证');
            }
            $id      = db('audit_materials')->insertGetId(['prove' => !empty($data['prove']) ? serialize($prove) : '', 'materials_remarks' => $data['materials_remarks'], 'capital_id' => $data['capital_id'], 'user_id' => $this->us['user_id'], 'creationtime' => time(), 'store_id' => $this->us['store_id'],]);
            $capital = db('capital')->where('capital_id', $data['capital_id'])->find();
            if ($capital['square'] != $data['square']) {
                db('capital')->where('capital_id', $data['capital_id'])->update(['square' => $data['square'], 'to_price' => $data['square'] * $capital['un_Price'], 'acceptance' => $id]);
                // $where[] = ['exp', Db::raw("FIND_IN_SET(" . $data['capital_id'] . ",capital_id)")];
//                $through = db('through')->where(['order_ids' => $capital['ordesr_id'], 'baocun' => 1])->where($where)->find();
//                if ($through) {
//                    $sum = db('capital')->where(['ordesr_id' => $capital['ordesr_id'], 'types' => 1, 'enable' => 1])->sum('to_price');
//                    db('through')->where(['order_ids' => $capital['ordesr_id'], 'baocun' => 1])->update(['amount' => $sum]);
//                }
            } else {
                db('capital')->where('capital_id', $data['capital_id'])->update(['acceptance' => $id]);
            }
            db()->commit();
            $oredr_count = db('capital')->where(['ordesr_id' => $capital['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            $oredr       = db('capital')->where('<acceptan></acceptan>ce', '<>', 0)->where(['ordesr_id' => $capital['ordesr_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
            if ($oredr == $oredr_count) {
                db('order')->where(['order_id' => $capital['ordesr_id']])->update(['acceptance_time' => time()]);
            }
            json_decode(sendOrder($capital['ordesr_id']), true);
            r_date([], 200, '操作成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /*
     *
     * 开工设置
     */
    public function userlist() {
        $data = $this->model->post(['order_id']);
        $de   = db('startup')->where('orders_id', $data['order_id'])->field('sta_time,up_time,con,handover,xiu_id')->find();
        if ($de) {
            if (!empty($de['xiu_id'])) {
                $app_user = Db::connect(config('database.db2'))->table('app_user')->whereIn('app_user.id', $de['xiu_id'])->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_user.responsible,app_work_type.title')->select();
                $order_id = $data['order_id'];
                foreach ($app_user as $k => $value) {
                    $app_user[$k]['leader'] = Db::connect(config('database.db2'))->table('app_user_order')->where('order_id', $order_id)->where('user_id', $value['user_id'])->value('leader');
                    $work_tag               = empty($value['work_tag']) ? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
                    $data                   = [];
                    foreach ($work_tag as $ks => $valu) {
                        switch ($ks) {
                            case 0:
                                $values = '漆工';
                                break;
                            case 1:
                                $values = '砖工';
                                break;
                            case 2:
                                $values = '抹灰工';
                                break;
                            case 3:
                                $values = '水电工';
                                break;
                            case 4:
                                $values = '室内防水工';
                                break;
                            case 5:
                                $values = '墙板安装工';
                                break;
                            case 6:
                                $values = '室内防水快修工';
                                break;
                            case 7:
                                $values = '高空作业防水工';
                                break;
                        }
                        if ($valu == 1) {
                            $data[] = $values;
                        }
                        
                    }
                    
                    $app_user[$k]['work_tag'] = implode(',', $data);
                    $app_user[$k]['check']    = false;
                }
                $de['shi'] = $app_user;
            } else {
                $de['shi'] = [];
            }
            $de['sta_time'] = !empty($de['sta_time']) ? date('Y-m-d H:i', $de['sta_time']) : '';
            $de['up_time']  = !empty($de['up_time']) ? date('Y-m-d H:i', $de['up_time']) : '';
            $de['handover'] = !empty($de['handover']) ? unserialize($de['handover']) : null;
        } else {
            $de = null;
        }
        
        r_date($de, 200);
        
    }
    
    /*
    * 获取师傅
    */
    public function get_master(Common $common,RedisPackage $redis) {
        
        $data               = \request()->post();
        $app_user_quit_jobs = null;
        $app_user           = Db::connect(config('database.db2'))->table('app_user')->where('app_user.checked', 1);
        if (isset($data['username']) && $data['username'] != '') {
            $app_user->whereLike('app_user.username', "%{$data['username']}%");
        }
        if (isset($data['order_id']) && $data['order_id'] != '' && $data['order_id'] != 0) {
            $startup            = Db::connect(config('database.db2'))->table('startup')->where('orders_id', $data['order_id'])->find();
            $app_user_quit_jobs = Db::connect(config('database.db2'))->table('app_user')->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->join('app_assist_master', 'app_assist_master.app_user_id=app_user.id', 'left')->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->where('if(app_user.origin=2,app_assist_master.certification=1,app_user.status=1)')->where('app_user.quit_jobs', 1)->where('app_user.test_account', 0)->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,if(app_user.origin=2,"协作师傅","自营") as origin,app_user.origin as origins,app_user.status,app_user.username,if(app_user.status=1,app_user.mobile,"已禁用") as mobile,store.store_name,ifnull(app_work_type.title,0) as title,app_assist_master.work_type_id,app_user.assist')->whereIn('app_user.id', $startup['xiu_id'])->select();
        }
        if (isset($data['store_id']) && $data['store_id'] != 0) {
            $app_user->where('app_user.store_id', $data['store_id']);
        }
        if (isset($data['work_type_id']) && $data['work_type_id'] != 0) {
            $app_user->where('app_user.work_type_id', $data['work_type_id']);
        }
        if (isset($data['origin']) && $data['origin'] != 0) {
            $app_user->where('app_user.origin', 2);
        }
        $user = $app_user->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->join('app_assist_master', 'app_assist_master.app_user_id=app_user.id', 'left')->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->where('app_user.status', 1)->where('if(app_user.origin=2,app_assist_master.certification=1,app_user.status=1)')->where('app_user.quit_jobs', 0)->where('app_user.test_account', 0)->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,if(app_user.origin=2,"协作师傅","自营") as origin,app_user.origin as origins,app_user.status,app_user.username,if(app_user.status=1,app_user.mobile,"已禁用") as mobile,store.store_name,ifnull(app_work_type.title,0) as title,app_assist_master.work_type_id,app_user.assist')->select();
        if (!empty($app_user_quit_jobs)) {
            $user = array_merge($user, $app_user_quit_jobs);
        }
        $checkHasFullSchedule=$common->checkHasFullSchedule(array_column($user,'user_id'));
        foreach ($user as $k => $value) {
            
            $work_tag = empty($value['work_tag']) ? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
            if ($value['title'] == 0 && $value['origins'] == 2) {
                $title             = \db('app_work_type')->whereIn('id', $value['work_type_id'])->column('title');
                $user[$k]['title'] = implode($title, ',');
            }
            $dataList = [];
            foreach ($work_tag as $ks => $valu) {
                switch ($ks) {
                    case 0:
                        $values = '漆工';
                        break;
                    case 1:
                        $values = '砖工';
                        break;
                    case 2:
                        $values = '抹灰工';
                        break;
                    case 3:
                        $values = '水电工';
                        break;
                    case 4:
                        $values = '室内防水工';
                        break;
                    case 5:
                        $values = '墙板安装工';
                        break;
                    case 6:
                        $values = '室内防水快修工';
                        break;
                    case 7:
                        $values = '高空作业防水工';
                        break;
                }
                if ($valu == 1) {
                    $dataList[] = $values;
                }
                
            }
            $user[$k]['color'] = 0;
            $user[$k]['id']    = 0;
            $workStatus=1;
            foreach($checkHasFullSchedule as  $k1=>$item){
               if($k1==$value['user_id'] && $item){
                 $workStatus=2;
                } 
            }
            $user[$k]['workStatus']    = $workStatus;
            if ($value['origins'] == 2) {
                $user[$k]['work_tag'] = implode(',', Db::connect(config('database.db2'))->table('app_work_type')->whereIn('id', $value['work_type_id'])->column('title'));
            } else {
                $user[$k]['work_tag'] = implode(',', $dataList);
            }
            
            if ($value['store_id'] == $this->us['store_id'] && $value['status'] == 1) {
                $user[$k]['color'] = 2;
            }
            if ($value['assist'] == 1) {
                $user[$k]['color'] = 1;
            }
            if ($value['store_id'] != $this->us['store_id'] && $value['status'] == 1 && $value['assist'] != 1) {
                $user[$k]['color'] = 0;
            }
            $user[$k]['sortTag'] = $user[$k]['color'];
            if (strpos($value['username'], "外协派单临时号") !== false) {
                $user[$k]['sortTag'] = 3;
            }
            $user[$k]['time'] = '';
            if (isset($data['projectId']) && $data['projectId'] != 0) {
                $userdate = $redis->get("DateAssignment-".md5($data['order_id'] . $data['projectId'] . 'time'));
                $date = 0;
                if ($userdate) {
                    $userdateList = json_decode($userdate, true);
                    foreach ($userdateList  as $v) {
                        if ($v['userId'] == $value['user_id']) {
                            $date = $v['time'];
                        }
                    }
                }
                 if(empty($userdate) || !in_array($value['user_id'],array_column($userdateList,'userId'))){
                     $app_user_confirm_order =db('app_user_confirm_order')->where('order_id',$data['order_id'])->where('app_user_id',$value['user_id'])->where('project_id',$data['projectId'])->where('status','<>',2)->where('delete_time',0)->find();
                      $date=$app_user_confirm_order['date'];
                     if($app_user_confirm_order['edit_time'] !=0){
                        $date=$app_user_confirm_order['edit_time'];
                     }
                      $date=$date * 1000;
                }
                if (isset($date)  && !empty($date) ) {
                    $user[$k]['time'] = $date;
                }
            }
            
        }
        $last_names = array_column($user, 'color');
        array_multisort($last_names, SORT_DESC, $user);
        r_date(['chen' => $user], 200);
    }
    
    /*
        *
        * 联系工程师
        */
    public function engineer() {
        $data    = $this->model->post(['order_id']);
        $results = send_post(UIP_SRC . "/support-v1/user/order-user", ['order_id' => $data['order_id'], 'city' => config('city')]);
        
        $results = json_decode($results, true);
        
        if (!empty($results) && $results['code'] == 200) {
            $chen = [];
            foreach ($results['data'] as $i) {
                if (!empty($i)) {
                    $i['origins']=0;
                    if($i['assist']==0){
                        $i['origins']=1;
                    }
                    $chen[] = $i;
                }
                
            }
            $da['chen'] = $chen;
            
            r_date($da, 200);
        } else {
            r_date([], 300, $results['msg']);
        }
        
    }
        /*
        *
        * 获取订单派单联系工程师
        */
    public function dispatchUser() {
        $data    = $this->model->post(['order_id']);
        $results = send_post(UIP_SRC . "/support-v1/user/order-user", ['order_id' => $data['order_id'], 'city' => config('city')]);
        $results = json_decode($results, true);
    
        if (!empty($results) && $results['code'] == 200) {
            $chen = [];
            foreach ($results['data'] as $i) {
                if (!empty($i)) {
                    $i['origins']=0;
                    if($i['assist']==0){
                        $i['origins']=1;
                    }
                    $chen[] = $i;
                }
                
            }
            $da['chen'] = $chen;
            
            r_date($da, 200);
        } else {
            r_date([], 300, $results['msg']);
        }
        
    }
    
    public function PaymentMethods() {
        $data = $this->model->post(['type']);
        //支付宝（重庆）https://images.yiniao.co/static/paycode/alipay_cq.jpg
        //微信（重庆）https://images.yiniao.co/static/paycode/wepay_cq.jpg
        if ($data['type'] == 3) {
            $url = 'https://images.yiniao.co/static/paycode/wepay_cd_wh_gy.jpg';
        } elseif ($data['type'] == 4) {
            $url = 'https://images.yiniao.co/static/paycode/alipay_cd_wh_gy.jpg';
        } elseif ($data['type'] == 7) {
            $url = 'https://images.yiniao.co/static/paycode/haoda_all.jpg';
        }
        r_date($url, 200);
    }
    
    /**
     * 发起收款
     */
    public function payment(OrderModel $orderModel, \app\api\model\Common $common) {
        $data = $this->model->post(['logos', 'weixin', 'orders_id', 'material', 'agency_material', 'uptime']);
        db()->startTrans();
        try {
            if ($data['weixin'] == 0) {
                throw new Exception('请选择付款方式');
            }
            $money = $data['material'] + $data['agency_material'];
            if ($money < 0) {
                throw new Exception('请走退款通道');
            }
            $lyu   = $orderModel->offer($data['orders_id'], 2);
            $money = $data['material'] + $data['agency_material'];
            if ($data['weixin'] != 2 && empty($data['logos'])) {
                throw new Exception('请上传图片');
            }
            $Common = $common::order_for_payment($data['orders_id']);
            if ($lyu['amount'] - $lyu['agency'] != 0) {
                if (sprintf('%.2f', $lyu['amount'] - $lyu['agency'] - $Common[0]) < $data['material']) {
                    throw new Exception('主合同金额错误');
                }
            }
            if ($lyu['agency'] != 0) {
                if (sprintf('%.2f', $lyu['agency'] - $Common[1]) < $data['agency_material']) {
                    throw new Exception('代购主材金额错误');
                }
            }
            if ($lyu['agency'] == 0 && $data['agency_material'] > 0) {
                $data['agency_material'] = 0;
            }
            if ($data['agency_material'] == 0 && $data['material'] == 0) {
                throw new Exception('金额错误');
            }
            $orderList = db('order')->join('user', 'order.assignor=user.user_id ', 'left')->where(['order.order_id' => $data['orders_id']])->field('user.store_id,order.state,order.company_id')->find();
            //有没有转派过
            $message = db('message')->where(['order_id' => $data['orders_id'], 'type' => 6])->order('id desc')->select();
            if (count($message) > 1) {
                $store_id = $orderList['store_id'];
            } else {
                $store_id = $this->us['store_id'];
            }
            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->value('company_id');
            
            $orderState = 0;
            $orderArray = [];
            //签约加金额审核
            if ($orderList['state'] == 3 && $data['weixin'] != 2) {
                $orderArray['state'] = 4;
                $orderState          = 4;
                remind($data['orders_id'], 4);
                $common->CommissionCalculation($data['orders_id'], $orderModel, 2);
            }
            if (empty($orderList['company_id'])) {
                $orderArray['company_id'] = $company_id;
                
            }
            if (!empty($orderArray)) {
                db('order')->where(['order.order_id' => $data['orders_id']])->update($orderArray);
            }
            $created_time = time();
            db('payment')->insertGetId(['uptime' => strtotime($data['uptime']),//实际完工时间
                'logos' => !empty($data['logos']) ? serialize(json_decode($data['logos'], true)) : '',//图片
                'material' => $data['material'], 'agency_material' => $data['agency_material'], 'money' => $money,//合计
                'orders_id' => $data['orders_id'], 'weixin' => $data['weixin'], 'created_time' => $created_time]);
            \db('order_times')->where('order_id', $data['orders_id'])->where('first_payment_time', 0)->update(['first_payment_time' => $created_time]);
            $common->MultimediaResources($data['orders_id'], $this->us['user_id'], !empty($data['logos']) ? json_decode($data['logos'], true) : [], 7);
            db()->commit();
            sendOrder($data['orders_id']);
            if ($orderState == 4) {
                $common->CommissionCalculation($data['orders_id'], $orderModel, 2);
                $Client = new \app\api\model\KafkaProducer();
                $Client->add($data['orders_id'], 'u8c_bdjobbasfil_save');
                
            }
            
            r_date([], 200, '新增成功');
            
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
     * 通联获取收款二维码
     */
    
    public function GetQRcode(\app\api\model\PayModel $payModel, \app\api\model\Common $common) {
        $data            = $this->model->post(['weixin', 'orderId', 'material', 'agency_material']);
        $money           = $data['material'] + $data['agency_material'];
        $expiration_time = strtotime('+' . $payModel::validtime . 'minute');
        $payment         = db('payment')->insertGetId(['logos' => '',//图片
            'material' => $data['material'], 'agency_material' => $data['agency_material'], 'money' => $money,//合计
            'orders_id' => $data['orderId'], 'weixin' => $data['weixin'], 'created_time' => time(), 'pay_type' => 1, 'expiration_time' => $expiration_time,]);
        $received_time   = db('order')->join('goods_category go', 'order.pro_id=go.id', 'left')->where(['order.order_id' => $data['orderId']])->field('order.order_no,order.company_id,go.title')->find();
        
        // $message = db('message')->where(['order_id' => $data['orderId'], 'type' => 6])->order('id desc')->select();
        // if (count($message) > 1) {
        //     $store_id = db('order')->join('user', 'order.assignor=user.user_id ', 'left')->where(['order.order_id' => $data['orderId']])->value('user.store_id');
        // } else {
        //     $store_id = $this->us['store_id'];
        // }
        // $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $store_id])->where('status', 1)->find();
        
        if (!empty($received_time['company_id'])) {
            
            $encryption = $common->encryption($received_time['company_id']);
        } else {
            
            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $this->us['store_id']])->where('status', 1)->find();
            
            $encryption[0] = $company_id['allpay_cusid'];
            $encryption[1] = $company_id['allpay_key'];
            $encryption[2] = $company_id['allpay_appid'];
            db('order')->where(['order.order_id' => $data['orderId']])->update(['company_id' => $company_id['company_id']]);
        }
        
        $s = $payModel->pay(['project' => $payment, 'money' => round($money, 2), 'order_no' => $received_time['order_no'], 'title' => $received_time['title'], 'cusid' => $encryption[0], 'key' => $encryption[1], 'APP_ID' => $encryption[2]]);
        db('payment')->where(['payment_id' => $payment])->update(['or_code' => $s]);
        r_date(['url' => $s, 'data' => '请在' . date('d', time()) . '日' . date('H点i分', $expiration_time) . '前完成支付', 'payment_id' => $payment, 'accountTips' => "支付时认准收款帐户为签约公司或成都益鸟科技有限公司"], 200);
        
    }
    
    /**
     * @param mixed 查询收款码
     */
    public function QueryCollectionCode() {
        $data     = $this->model->post(['order_id']);
        $request  = Request::instance();
        $pa       = db('payment')->where(['orders_id' => $data['order_id']])->order('payment_id desc')->field('weixin,pay_type,payment_id,or_code')->find();
        $recharge = 0;
        if ($pa['weixin'] == 2 && $pa['pay_type'] == 1) {
            $domain   = $request->domain();
            $recharge = db('recharge')->join('payment', 'payment.payment_id=recharge.project', 'left')->where(['payment.payment_id' => $pa['payment_id']])->where('payment.expiration_time', '>', time())->where('recharge.status', 0)->order('recharge.recharge_id desc')->field('recharge.order_nos,payment.money,payment.expiration_time,payment.payment_id')->find();
        }
        if (!empty($recharge)) {
            $AcceptData = ['url' => $pa['or_code'], 'money' => $recharge['money'], 'data' => '请在' . date('d', time()) . '日' . date('H点i分', $recharge['expiration_time']) . '前完成支付', 'payment_id' => $recharge['payment_id'], 'accountTips' => "支付时认准收款帐户为签约公司或成都益鸟科技有限公司"];
        } else {
            $AcceptData = null;
        }
        r_date($AcceptData, 200);
    }
    
    /*
     * 剩余款项
     */
    public function surplus($order_id) {
        
        $list = (new OrderModel())->TotalProfit($order_id);
        
        $Common                = \app\api\model\Common::order_for_payment($order_id);
        $da['material']        = 0;
        $da['agency_material'] = 0;
        if (!empty($list['MainMaterialMoney'])) {
            $da['material'] = round($list['MainMaterialMoney'] - $Common[0], 2);
        }
        if (!empty($list['agencyMoney'])) {
            $da['agency_material'] = round($list['agencyMoney'] - $Common[1], 2);
        }
        r_date($da, 200, '新增成功');
    }
    
    /*
     * 收款记录
     */
    public function CollectionRecord(Approval $approval) {
        $data = $this->model->post(['order_id']);
        
        $at                     = db('payment')->where('orders_id', $data['order_id'])->select();
        $orderSetting           = db('order_setting')->where('order_id', $data['order_id'])->value('payment_type');
        $main_payment_ok_price  = 0;
        $agent_payment_ok_price = 0;
        $materialMoeny          = 0;
        $agency_material        = 0;
        foreach ($at as $K => $item) {
            $at[$K]['cleared_time'] = empty($item['cleared_time']) ? '' : date('Y-m-d H:i', $item['cleared_time']);
            $at[$K]['logos']        = empty($item['logos']) ? null : unserialize($item['logos']);
            $at[$K]['state']        = empty($item['cleared_time']) ? 1 : 2;
            $materialMoeny          += $item['material'];
            $agency_material        += $item['agency_material'];
            if (!empty($at[$K]['cleared_time'])) {
                $main_payment_ok_price  += $item['material'];
                $agent_payment_ok_price += $item['agency_material'];
            }
            $at[$K]['uptime']          = empty($item['uptime']) ? '' : date('Y-m-d H:i', $item['uptime']);
            $at[$K]['expiration_time'] = empty($item['expiration_time']) ? '' : date('Y-m-d H:i', $item['expiration_time']);
            if ($item['weixin'] == 2 && $item['pay_type'] == 1) {
                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', 9));
            } else {
                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $item['weixin']));
            }
            $at[$K]['weixin'] = isset($company[0]['title']) ? $company[0]['title'] : '';
            if ($item['material'] == 0.00 && $item['agency_material'] == 0.00) {
                $material = $item['money'];
            } elseif ($item['material'] != 0.000) {
                $material = $item['material'];
            } else {
                $material = 0;
            }
            $at[$K]['material'] = $material;
            $at[$K]['type']     = $item['weixin'];
            if ($orderSetting == 1 && (($item['weixin'] == 6 || $item['weixin'] == 8 || $item['weixin'] == 1) && empty($item['cleared_time']))) {
                $at[$K]['state'] = 1;
            }
            
        }
//        $offer               = $orderModel->TotalProfit($data['order_id']);
//        $all_amount_main     = strval($offer['MainMaterialMoney']);
//        $all_amount_agency   = strval($offer['agencyMoney']);
//        $list['masterContractHasBeenRecorded'] = 0;
//        if ($all_amount_main != 0.00) {
//            $list['masterContractHasBeenRecorded'] = sprintf("%.2f", ($main_payment_ok_price / $all_amount_main) * 100);
//        }
//        $list['agentPurchaseContractHasBeenRecorded'] = 0;
//        if ($all_amount_agency != 0.00) {
//            $list['agentPurchaseContractHasBeenRecorded'] = sprintf("%.2f", ($agent_payment_ok_price / $all_amount_agency) * 100);
//        }
//        $list['total_price'] = (string)($all_amount_main+$all_amount_agency);
//        $list['main_payment_price'] = (string)$materialMoeny;
//        $list['agent_payment_ok_price'] = (string)$agent_payment_ok_price;
//        $list['main_payment_ok_price'] = (string)$main_payment_ok_price;
//        $list['masterContractUnderReview'] =(string)($materialMoeny-$main_payment_ok_price);
//        $list['agentPurchaseContractUnderReview'] = (string)($agency_material-$agent_payment_ok_price);
//        $list['agent_payment_price'] =(string) $agency_material;
//        $list['masterContractCollection'] = (string)($all_amount_main-$list['main_payment_price']);
//        $list['agentPurchaseContractCollection'] = (string)($all_amount_agency-$list['agent_payment_price']);
//        $list['overallProgress'] = $list['main_payment_price'] + $list['agent_payment_price'] . '/' . $list['total_price'];
//        $list['list'] = $at;
        r_date($at, 200);
    }
    
    /*
    * 收款所有
    */
    public function CollectionRecordAll(Approval $approval) {
        $data = $this->model->post(['time', 'state', 'keywords']);
        $at   = db('payment')->join('order', 'order.order_id=payment.orders_id', 'left')->join('province p', 'order.province_id=p.province_id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left');
        if (isset($data['time']) && $data['time'] != '') {
            $start_time = strtotime(date('Y-m-d 0:0:0', strtotime($data['time'])));
            //当天结束之间
            $end_time = $start_time + 60 * 60 * 24;
            $at->whereBetween('payment.created_time', [$start_time, $end_time]);
        }
        if (isset($data['state']) && $data['state'] != 0) {
            if ($data['state'] == 1) {
                $at->whereNull('payment.cleared_time');
            } elseif ($data['state'] == 2) {
                $at->whereNotNull('payment.cleared_time');
            } else {
                
                $at->whereNotNull('payment.reject');
            }
        }
        if (isset($data['keywords']) && $data['keywords'] != '') {
            $at->where('order.addres|order.order_no', 'like', "%{$data['keywords']}%");
        }
        $at = $at->field('concat(p.province,c.city,y.county,order.addres) as addres,payment.payment_id,payment.reject,payment.success,order.order_no,payment.money,payment.weixin,payment.pay_type,(payment.material+payment.agency_material) as money,FROM_UNIXTIME(payment.created_time,"%Y年%m月%d日") as created_time,payment.cleared_time')->where('order.assignor', $this->us['user_id'])->order('payment.payment_id desc')->select();
        
        
        foreach ($at as $K => $item) {
            if (!empty($item['cleared_time']) && empty($item['reject'])) {
                $at[$K]['cleared_time'] = "审核通过";
            } else if (empty($item['cleared_time']) && !empty($item['reject'])) {
                $at[$K]['cleared_time'] = "驳回";
            }
            if (($item['success'] == 1 || $item['success'] == 3) && $item['weixin'] == 2) {
                $at[$K]['success'] = "未支付";
            } else {
                $at[$K]['success'] = "已支付";
            }
            if ($item['weixin'] == 2 && $item['pay_type'] == 1) {
                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', 9));
            } else {
                $company          = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $item['weixin']));
            }
            $at[$K]['weixin'] = empty($company)?"其它":$company[0]['title'];
            
        }
        r_date($at, 200);
    }
    
    /*
    * 收款所有
    */
    public function CollectionRecordIndo(Approval $approval) {
        $data = $this->model->post(['payment_id']);
        
        $at = db('payment')->join('order', 'order.order_id=payment.orders_id', 'left')->join('province p', 'order.province_id=p.province_id', 'left')->join('goods_category go', 'order.pro_id=go.id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left')->field('concat(p.province,c.city,y.county,order.addres) as addres,go.title,order.order_no,order.order_id,payment.logos,payment.reject,payment.money,payment.weixin,payment.pay_type,payment.material,payment.agency_material,FROM_UNIXTIME(payment.created_time,"%Y年%m月%d日") as created_time,payment.success,payment.cleared_time')->where('payment.payment_id', $data['payment_id'])->find();
        
        if (!empty($at['cleared_time'])) {
            $at['cleared_time'] = date('Y-m-d H:i:s', $at['cleared_time']);
            $at['state']        = "审核通过";
            $at['cleared_name'] = "孙悦";
        } else {
            $at['cleared_time'] = "";
            $at['cleared_name'] = "孙悦";
        }
        
        if (!empty($at['reject'])) {
            $at['cleared_time'] = " ";
            $at['cleared_name'] = "孙悦";
            $at['state']        = "驳回";
        }
        if (($at['success'] == 1 || $at['success'] == 3) && $at['weixin'] == 2) {
            $at['success'] = "未支付";
        } else {
            $at['success'] = "已支付";
        }
        if ($at['weixin'] == 2 && $at['pay_type'] == 1) {
            $company      = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', 9));
            $at['weixin'] = $company[0]['title'];
        } else {
            $company      = array_values($approval->filter_by_value($this->PaymentMethod(2), 'id', $at['weixin']));
            $at['weixin'] = $company[0]['title'];
        }
        $at['logos'] = empty($at['logos']) ? null : unserialize($at['logos']);
        if ($at['material'] == 0.00 && $at['agency_material'] == 0.00) {
            $material = $at['money'];
        } elseif ($at['material'] != 0.000) {
            $material = $at['material'];
        } else {
            $material = 0;
        }
        $at['material'] = $material;
        
        
        r_date($at, 200);
    }
    
    /*
    * 订单付款渠道
    */
    public function PaymentMethod($type = 1) {
        
        $payment_config = \db('payment_config', config('database.zong'))->where('status', 1)->where('city', config('cityId'))->find();
        $compile        = json_decode($payment_config['compile'], true);
        $content3       = json_decode($payment_config['content3'], true);
        $content        = json_decode($payment_config['content'], true);
        if ($type == 1) {
            $get         = Request::instance()->get();
            $paymentList = array_merge($content, $content3);
            if (isset($get['orderId'])) {
                $orderFind        = \db('order')->field('order.channel_id,order_setting.payment_switch_1,if(order_setting.payment_type =3,1,0) as shell')->join('order_setting', 'order_setting.order_id=order.order_id')->where('order.order_id', $get['orderId'])->find();
                $payment_switch_1 = $orderFind['payment_switch_1'];
                $channel_id       = $orderFind['channel_id'];
                if ($orderFind['shell'] == 1) {
                    $array = [];
                    foreach ($paymentList as $list) {
                        //淘宝
                        if ($list['id'] == 12) {
                            $array[] = $list;
                            
                        }
                    }
                } else {
                    if (($channel_id == 11 || $channel_id == 40 || $channel_id == 41) && $payment_switch_1 == 2) {
                        $array = [];
                        foreach ($paymentList as $list) {
                            //淘宝
                            if ($list['id'] == 5 && $channel_id == 11) {
                                $array[] = $list;
                                
                            } elseif ($list['id'] == 10 && $channel_id == 40) {
                                //天猫
                                $array[] = $list;
                            } elseif ($list['id'] == 11 && $channel_id == 41) {
                                $array[] = $list;
                            }
                        }
                        $paymentList = $array;
                        
                    }
                }
                
            }
            
            r_date($paymentList, 200);
        } else {
            return array_merge($compile, $content3);
        }
    }
    
    function object2array(&$object) {
        $object = json_decode(json_encode($object), true);
        return $object;
    }
    
    public function unit() {
        $object = db('unit')->field('title,id')->select();
        
        r_date($object, 200);
    }
    
    /*
     * 支付是否成功轮询查询
     */
    public function CollectionInquiry(OrderModel $orderModel, \app\api\model\Common $common) {
        $data       = $this->model->post(['payment_id']);
        $payment_id = db('payment')->where('payment_id', $data['payment_id'])->join('order', 'order.order_id=payment.orders_id', 'left')->field('payment.success,order.state,order.order_id')->find();
        if ($payment_id['success'] == 2) {
            if ($payment_id['state'] == 3) {
                $paymentMoney = db('payment')->where('payment.orders_id', $payment_id['order_id'])->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')->sum('money');
                \db('order_times')->where('order_id', $payment_id['order_id'])->where('first_payment_time', 0)->update(['first_payment_time' => time()]);
                $total_price = db('order_aggregate')->where('order_id', $payment_id['order_id'])->value('total_price');
                if ($paymentMoney / $total_price >= 0.499) {
                    $order_payment_nodes = db('order_payment_nodes', config('database.zong'))->where('order_id', $payment_id['order_id'])->where('payment_id', $data['payment_id'])->find();
                    $offer               = $orderModel->TotalProfit($payment_id['order_id']);
                    $all_amount_main     = strval($offer['MainMaterialMoney']);
                    $all_amount_agency   = strval($offer['agencyMoney']);
                    if (bcadd($all_amount_main, $all_amount_agency, 2) >= 10000 || ($all_amount_main < 10000 && $order_payment_nodes != 0) || $all_amount_main == '0.00' || $paymentMoney >= bcadd($all_amount_main, $all_amount_agency, 2)) {
                        db('order')->where(['order_id' => $payment_id['order_id']])->update(['state' => 4]);
                        remind($payment_id['order_id'], 4);
                        $Client = new \app\api\model\KafkaProducer();
                        $Client->add($payment_id['order_id'], 'u8c_bdjobbasfil_save');
                    }
                }
                
            }
            $sata = 1;
        } else {
            $sata = 2;
        }
        r_date(['success' => $sata], 200);
    }
    
    /**
     * 视频节点
     */
    public function jie() {
        
        $data    = $this->model->post(['order_ids']);
        $results = send_post(UIP_SRC . "/support-v1/node/list?order_id=" . $data['order_ids'] . "&city=" . config('city'), [], 2);
        $results = json_decode($results);
        if ($results->code == 200) {
            r_date($results->data, 200);
        } else {
            r_date([], 200, $results->msg);
        }
        
    }
    
    
    /*
    *
    * 订单发起返工
    */
    public function fan() {
        $data = $this->model->post();
        db()->startTrans();
        try {
            $order_rework = db('order_rework')->where(['rework_end' => $data['id']])->find();
            if (empty($order_rework)) {
                throw  new  Exception('信息不存在');
            }
            db('order')->where('order_id', $data['order_id'])->update(['rework' => 1]);
            db('order_log')->insert(['admin_type' => 1, 'admin_id' => $this->us['user_id'], 'create_time' => time(), 'order_id' => $data['order_id'], 'content' => '店长APP发起返工']);
            db('order_rework')->where(['rework_end' => $data['id']])->update(['master_id' => $data['master_id'],]);
            
            db()->commit();
            sendOrder($data['order_id']);
            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
    *
    * 订单发起返工获取师傅
    */
    public function MasterFanGong() {
        $data         = $this->model->post();
        $order_rework = db('order_rework')->where(['order_id' => $data['order_id'], 'rework_end' => $data['id']])->column('master_id');
        
        if (!empty($order_rework[0])) {
            
            $app_user = Db::connect(config('database.db2'))->table('app_user')->where('app_user.checked', 1)->where('app_user.status', 1);
            $user     = $app_user->join('app_work_type', 'app_work_type.id=app_user.work_type_id', 'left')->where('app_work_type.status', 1)->join(config('database')['database'] . '.store', 'app_user.store_id=store.store_id', 'left')->field('app_user.id as user_id,app_user.store_id,app_user.work_tag,app_user.online,app_user.username,app_user.mobile,store.store_name,app_work_type.title')->whereIn('app_user.id', explode(',', $order_rework[0]))->select();
            foreach ($user as $k => $value) {
                $work_tag = empty($value['work_tag']) ? [0, 0, 0, 0, 0, 0, 0, 0] : explode(',', $value['work_tag']);
                $data     = [];
                foreach ($work_tag as $ks => $valu) {
                    switch ($ks) {
                        case 0:
                            $values = '漆工';
                            break;
                        case 1:
                            $values = '砖工';
                            break;
                        case 2:
                            $values = '抹灰工';
                            break;
                        case 3:
                            $values = '水电工';
                            break;
                        case 4:
                            $values = '室内防水工';
                            break;
                        case 5:
                            $values = '墙板安装工';
                            break;
                        case 6:
                            $values = '室内防水快修工';
                            break;
                        case 7:
                            $values = '高空作业防水工';
                            break;
                    }
                    if ($valu == 1) {
                        $data[] = $values;
                    }
                    
                }
                $user[$k]['work_tag'] = implode(',', $data);
                if ($value['store_id'] == $this->us['store_id']) {
                    $user[$k]['color'] = 1;
                } else {
                    $user[$k]['color'] = 0;
                }
                
            }
            $last_names = array_column($user, 'color');
            array_multisort($last_names, SORT_DESC, $user);
        }
        
        
        r_date(empty($user) ? [] : $user, 200, '成功');
        
    }
    
    /*
    *
    * 获取返工原因状态
    */
    public function ReturnWorkReson() {
        $data             = $this->model->post();
        $re               = db('order_rework')->where(['order_id' => $data['order_id']])->field('reason')->find();
        $reason['reason'] = $re['reason'];
        r_date($reason, 200);
        
    }
    
    /*
     * 订单主合同发起完工
     */
    public function ToBeFinished() {
        $data = $this->model->post(['order_id', 'selectType']); 
        db()->startTrans();
        try {
            $re = db('order')->field('order.start_time,order_setting.work_check as shell,order.agency_finish_time,order.finish_time,order.state')->join('order_setting', 'order.order_id=order_setting.order_id', 'left')->where('order.order_id', $data['order_id'])->find();
            if ($re['agency_finish_time'] != 0 && ($data['selectType'] == 2 || $data['selectType'] == 3)) {
                throw  new  Exception('代购已经完工');
            }
            if (($re['finish_time'] != 0 && $re['state'] != 4) && ($data['selectType'] == 1 || $data['selectType'] == 3)) {
                throw  new  Exception('主合同已经完工');
            }
            $envelopes_id = db('envelopes')->where('type', 1)->where('ordesr_id', $data['order_id'])->value('envelopes_id');
            $capitalList  = db('capital')->field('GROUP_CONCAT(capital_id) as capital_id,sum(if(agency=1,1,0)) as agency,sum(if(agency=0,1,0)) as man')->where('envelopes_id', $envelopes_id)->where('types', 1)->where('enable', 1)->select();
          
            if ((($capitalList[0]['agency'] != 0 && $capitalList[0]['man'] != 0) || $capitalList[0]['man'] != 0) && $data['selectType'] != 2) {
                $startup = db('startup')->where('orders_id', $data['order_id'])->find();
                //派单师傅
                $relation     = \db('app_user')->field('app_user.username,app_user.origin')->whereIn('id', $startup['xiu_id'])->select();
                $cooperation  = [];
                $cooperation1 = [];
                foreach ($relation as $item) {
                    if ($item['origin'] == 2) {
                        $cooperation[] = $item;
                    } else {
                        $cooperation1[] = $item;
                    }
                }
                if (empty($re['start_time']) && !empty($cooperation1)) {
                    throw  new  Exception('需要派单给师傅并点开工');
                } elseif (empty($re['start_time']) && empty($cooperation1) && !empty($cooperation) && $startup['sta_time'] == 0) {
                    throw  new  Exception('在更多操作中操作订单开工');
                } elseif (empty($re['start_time']) && empty($cooperation1) && empty($cooperation)) {
                    throw  new  Exception('需要派单给师傅并点开工');
                }
                
            }
            if ($capitalList[0]['agency'] != 0 && $capitalList[0]['man'] == 0) {
                if (empty($re['start_time'])) {
                    throw  new  Exception('在更多操作中操作订单开工');
                }
                
            }
            $finish_time = time();
            if ($re['shell'] == 1) {
                $order_acceptance = db('order_acceptance')->where('deleted_at', 0)->where(['order_id' => $data['order_id']])->count();
                if ($order_acceptance == 0) {
                    r_date(null, 201, '请添加完工验收单');
                }
                db('order_times')->where('order_id', $data['order_id'])->update(['acceptance_time' => $finish_time]);
            }
            if (($capitalList[0]['agency'] != 0 && $data['selectType'] == 1) || ($capitalList[0]['man'] == 0 && $data['selectType'] == 2) || $data['selectType'] == 3) {
               
                $work_check    = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $data['order_id']])->field('sum(if(state=0 or state=3,1,0)) as incomplete,sum(if(state !=0 or state !=3,1,0)) as Finished')->where('delete_time', 0)->group('order_id')->select();
                $work_checkImg = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $data['order_id']])->order('id desc')->where('work_title_id', 5)->where('delete_time', 0)->find();
                if (empty($work_checkImg['img']) && empty($work_checkImg['no_watermark_image'])) {
                    r_date(null, 201, '完工验收没有完成，无法完工，请根据完工验收提示进行验收');
                }
//                if (!empty($work_checkImg['img']) && !empty($work_checkImg['no_watermark_image']) && $work_checkImg['model']==2 && $work_checkImg['audit_status'] !=1) {
//                    r_date(null, 201, '完工验收没有完成，无法完工，请根据完工验收提示进行验收');
//                }
                $list_process = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'list_process')->find();
                $order_acceptance_content  = Db::connect(config('database.zong'))->table('order_acceptance_content')->where('work_check', $work_checkImg['id'])->find();
                $list_process = json_decode($list_process['valuess'], true);
                if ((empty($work_check) || $work_check[0]['incomplete'] != 0 || $work_check[0]['Finished'] != count($list_process)) && empty($order_acceptance_content)) {
                    r_date(null, 201, '完工验收没有完成，无法完工，请根据完工验收提示进行验收');
                }
            }
            if ($data['selectType'] == 1 || $data['selectType'] == 3) {
                if ($capitalList[0]['agency'] == 0 || ($capitalList[0]['agency'] != 0 && $re['agency_finish_time'] != 0) || ($re['agency_finish_time'] == 0 && $re['finish_time'] == 0 && $data['selectType'] == 3)) {
                    $finishData['state'] = 7;
                }
                $finishData['finish_time'] = $finish_time;
                Db::connect(config('database.db2'))->table('app_user_order')->where('status', '<>', 10)->where(['order_id' => $data['order_id']])->whereNull('deleted_at')->update(['all_finish_at' => $finish_time]);
            }
            if ($data['selectType'] == 2 || $data['selectType'] == 3) {
                if ($capitalList[0]['man'] == 0 || ($capitalList[0]['man'] != 0 && $re['finish_time'] != 0)) {
                    $finishData['state'] = 7;
                }
                $finishData['agency_finish_time'] = $finish_time;
            }
            if(isset($finishData['state']) &&  $finishData['state']==7){
                 openapiAddTask($data['order_id'],7,'店长完工','');
            }
            OrderModel::update($finishData, ['order_id' => $data['order_id']]);
            //完工推送
            (new Common())->PushCompletion(3, $data['order_id']);
            db()->commit();
            sendOrder($data['order_id']);
            //完工更行订单延期扣款和完工验收单
            (new Common())->allCompleted($data['order_id'],$this->us);
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
    }
    
    /*
     * 派发交付负责人，
     */
    public function distributionManager(OrderDeliveryManagerModel $deliveryManagerModel) {
        $data = Authority::param(['orderId', 'userId']);
        $deliveryManagerModel->addOrderDeliveryManager($data['orderId'], $data['userId']);
        \db('order')->where('order_id', $data['orderId'])->update(['deliverer' => $data['userId']]);
        r_date(null, 200);
    }
    
    /*
     * 返回状态返回施工中
     */
    public function Unsettled() {
        $data     = Authority::param(['order_id']);
        $order_id = $data['order_id'];
        $order    = db('order')->where('order_id', $order_id)->find();
        if (empty($order['cleared_time']) && empty($order['settlement_time'])) {
            db('order')->where(['order_id' => $order_id])->update(['state' => 4, 'finish_time' => null]);
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $order_id, 'status' => 4])->update(['status' => 3]);
            db('order_log')->insert(['admin_type' => 1, 'admin_id' => $this->us['user_id'], 'create_time' => time(), 'order_id' => $order_id, 'content' => '店长APP将订单状态从已完工状态（完工时间：' . date('Y-m-d H:i:s', $order['finish_time']) . '）恢复到施工中。']);
            $Client = new \app\api\model\KafkaProducer();
            $Client->add($order_id, 'u8c_bdjobbasfil_save');
            json_decode(sendOrder($order_id), true);
            r_date([], 200);
        }
        r_date([], 300, '该订单已结算不能返回施工中');
        
        
    }
    
    /*
     * 完工状态提示
     */
    public function completionStatusPrompt() {
        $data         = Authority::param(['orderId', 'type']);
        $list['zhu']  = [];
        $list['dai']  = [];
        $orderId      = $data['orderId'];
        $re           = db('order')->field('order.cleared_time,order.agency_finish_time,order.finish_time,order.settlement_time,order_aggregate.main_price,order_aggregate.agent_price,order_aggregate.main_payment_price,order_aggregate.agent_payment_price,order_aggregate.agent_payment_ok_price,order_aggregate.main_payment_ok_price,order.acceptance_time,order.state')->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'left')->where('order.order_id', $orderId)->find();
        $orderSetting = db('order_setting')->where(['order_id' => $orderId])->find();
        $order_times = db('order_times')->where(['order_id' => $orderId])->find();
        $envelopes_id = db('envelopes')->where('type', 1)->where('ordesr_id', $orderId)->value('envelopes_id');
        $capitalList  = db('capital')->field('GROUP_CONCAT(capital_id) as capital_id,sum(if(agency=1,1,0)) as agency,sum(if(agency=0,1,0)) as man')->where('envelopes_id', $envelopes_id)->where('types', 1)->where('enable', 1)->select();
        $capital      = $capitalList[0]['capital_id'];
        if ($data['type'] == 1) {
            $listAccepted               = ['title' => '施工节点清单', 'state' => 1, 'reason' => '', 'code' => 0];
            $auxiliary_interactiveState = 0;
            if ($order_times['change_work_time'] < 1748534400) {
                $auxiliary_interactive      = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $orderId)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->count();
                $auxiliary_interactiveCount = db('auxiliary_delivery_node')->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $orderId)->where('auxiliary_delivery_node.state', 1)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->column('auxiliary_delivery_node.auxiliary_delivery_schedul_id');
                if ($auxiliary_interactive > count(array_merge(array_unique($auxiliary_interactiveCount)))) {
                    $auxiliary_interactiveState = 1;
                }
            } else {
                $auxiliary_interactive      = db('auxiliary_project_list')->where('work_process_type', 1)->where('auxiliary_project_list.order_id', $orderId)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_project_list.completion_time')->count();
                if ($auxiliary_interactive != 0) {
                    $auxiliary_interactiveState = 1;
                }
            }


            if ($auxiliary_interactiveState == 1) {
                $listAccepted['state']  = 0;
                $listAccepted['reason'] = '施工节点未上传，无法完工，请去工地巡检上传节点';
                $listAccepted['code']   = 1;
            }
            $acceptance = ['title' => '清单验收', 'state' => 1, 'reason' => ''];
            if ($re['acceptance_time'] == 0 || empty($re['acceptance_time'])) {
                $capitalAcceptance = \db('capital')->where('ordesr_id', $orderId)->where('agency', 1)->where('types', 1)->where('enable', 1)->field('sum(if(acceptance=0,1,0)) as wei,sum(if(acceptance !=0,1,0)) as yi')->select();
                if ($capitalAcceptance[0]['wei'] == 0 && $capitalList[0]['agency']  != 0) {
                    \db('order')->where('order_id', $orderId)->update(['acceptance_time' => time()]);
                } else {
                    $acceptance['state']  = 0;
                    $acceptance['reason'] = '请验收后完工';
                    $acceptance['code']   = 11;
                    if ($orderSetting['stop_agent_reimbursement'] == 1) {
                        $acceptance['code']   = 2;
                    }
                }
            }
            $workCheck     = ['title' => '完工验收单', 'state' => 1, 'reason' => '', 'code' => 0];
            $work_check    = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $orderId])->field('sum(if(state=0 or state=3,1,0)) as incomplete,sum(if(state !=0 or state !=3,1,0)) as Finished')->where('delete_time', 0)->group('order_id')->select();
            $work_checkImg = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $orderId])->where('work_title_id', 5)->where('delete_time', 0)->find();
            $list_process  = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'list_process')->find();
            $order_acceptance_content  = Db::connect(config('database.zong'))->table('order_acceptance_content')->where('work_check', $work_checkImg['id'])->find();
            $list_process  = json_decode($list_process['valuess'], true);

            if ((empty($work_checkImg['img']) && empty($work_checkImg['no_watermark_image'])) || ((empty($work_check) || $work_check[0]['incomplete'] != 0 || $work_check[0]['Finished'] != count($list_process)) && empty($order_acceptance_content))) {
                $workCheck['state']  = 0;
                $workCheck['reason'] = '完工验收没有完成，无法完工，请根据完工验收提示进行验收(完工验收单在订单详情-施工管理-完工验收可进入）';
                $workCheck['code']   = 3;
            }
                 //有没有通过的有就不展示
            $order_completion_pass = Db::connect(config('database.zong'))->table('order_completion')->where(['order_id' => $orderId, 'inspection_type' => 3])->find();
            if (empty($order_completion_pass)) {
                $inspection_type1 = Db::connect(config('database.zong'))->table('order_completion')->order('id desc')->where(['order_id' => $orderId, 'inspection_type' => 2])->find();
                $acceptance_issue = db('acceptance_issue', config('database.zong'))->where(['order_completion_id' => $inspection_type1['id']])->find();
                if (!empty($inspection_type1) && empty($acceptance_issue)) {
                    $zhuCompletion1 = ['title' => '用户验收驳回待处理', 'state' => 0, 'reason' => '', 'code' => 13, 'id' => $inspection_type1['id']];
                    $daiCompletion1 = ['title' => '用户验收驳回待处理', 'state' => 0, 'reason' => '', 'code' => 13, 'id' => $inspection_type1['id']];
                }
            }
            
            if (($capitalList[0]['agency'] != 0 && $capitalList[0]['man'] != 0)) {
                array_push($list['zhu'], $listAccepted);
                array_push($list['dai'], $acceptance);
                array_push($list['zhu'], $workCheck);
                if (isset($zhuCompletion1)) {
                    array_push($list['zhu'], $zhuCompletion1);
                }
            } elseif ($capitalList[0]['man'] != 0 && $capitalList[0]['agency'] == 0) {
                array_push($list['zhu'], $listAccepted);
                array_push($list['zhu'], $workCheck);
                if (isset($zhuCompletion1)) {
                    array_push($list['zhu'], $zhuCompletion1);
                }
            } elseif ($capitalList[0]['man'] == 0 && $capitalList[0]['agency'] != 0) {
                array_push($list['dai'], $listAccepted);
                array_push($list['dai'], $workCheck);
                array_push($list['dai'], $acceptance);
                if (isset($daiCompletion1)) {
                    array_push($list['dai'], $daiCompletion1);
                }
            }

            if ($data['type'] == 1) {
                if ($capitalList[0]['agency'] != 0 && $re['agency_finish_time'] != 0 || ($capitalList[0]['agency'] == 0)) {
                    unset($list['dai']);
                }
                if ($capitalList[0]['man'] != 0 && ($re['finish_time'] != 0)) {
                    unset($list['zhu']);
                }
            }
        }
        if ($data['type'] == 2) {
            $visa_form   = db('visa_form')->where('order_id', $orderId)->whereNUll('signing_time')->value('capital_id');
            $visa_form   = db('capital')->whereIn('capital_id', $visa_form)->field('sum(if(agency=0,1,0)) as zhu,sum(if(agency=1,1,0)) as dai')->select();
            $capital     = db('capital')->where('ordesr_id', $orderId)->whereIn('approve', [3, 4, 5])->field('sum(if(agency=0,1,0)) as zhu,sum(if(agency=1,1,0)) as dai')->select();
            $manVisaForm = ['title' => '增项签证单', 'state' => 1, 'reason' => '', 'code' => 0];
            $daiVisaForm = ['title' => '增项签证单', 'state' => 1, 'reason' => '', 'code' => 0];
            if ((!empty($visa_form) != 0 && $visa_form[0]['zhu'] != 0) || $capital[0]['zhu'] != 0) {
                $manVisaForm['state']  = 0;
                $manVisaForm['reason'] = '还有正在进行的签证单没有签字，不能发起结算';
                $manVisaForm['code']   = 4;
            }
            if ((!empty($visa_form) != 0 && $visa_form[0]['dai'] != 0) || $capital[0]['dai'] != 0) {
                $daiVisaForm['state']  = 0;
                $daiVisaForm['reason'] = '还有正在进行的签证单没有签字，不能发起结算';
                $daiVisaForm['code']   = 4;
            }
            
            array_push($list['zhu'], $manVisaForm);
            array_push($list['dai'], $daiVisaForm);
            $manacceptance = ['title' => '上下道工序', 'state' => 1, 'reason' => '', 'code' => 12];
            $app_user_previous_acceptance=\db('app_user_previous_acceptance')->join('order', 'order.order_id=app_user_previous_acceptance.order_id')->where('app_user_previous_acceptance.standard', '<>',1)->where('app_user_previous_acceptance.state', 3)->where('order.assignor', $this->us['user_id'])->where('order.order_id', $orderId)->count();
            if ($capitalList[0]['man'] != 0 && $app_user_previous_acceptance>0) {
                $manacceptance['state']  = 0;
                $manacceptance['reason'] = '上下道工序不合格审核异常，不能发起结算';
                $manacceptance['code']   = 12;
            }
             array_push($list['zhu'], $manacceptance);
            $manPayment = ['title' => '收款金额', 'state' => 1, 'reason' => '', 'code' => 0];
            $daiPayment = ['title' => '收款金额', 'state' => 1, 'reason' => '', 'code' => 0];
            if (bcsub($re['main_payment_ok_price'], $re['main_payment_price'], 2) < 0 || bcsub($re['main_price'], $re['main_payment_price'], 2) < 0 || bcsub($re['main_price'], $re['main_payment_price'], 2) > 0) {
                $manPayment['state']  = 0;
                $manPayment['reason'] = '主合同收款金额异常，若要调账请财务，若要退款请操作退款';
                $manPayment['code']   = 7;
            }
            if (bcsub($re['agent_payment_ok_price'], $re['agent_payment_price'], 2) < 0 || bcsub($re['agent_price'], $re['agent_payment_price'], 2) < 0 || bcsub($re['agent_price'], $re['agent_payment_price'], 2) > 0) {
                $daiPayment['state']  = 0;
                $daiPayment['reason'] = '代购合同收款金额异常，若要调账请财务，若要退款请操作退款';
                $daiPayment['code']   = 7;
            }
            array_push($list['zhu'], $manPayment);
            array_push($list['dai'], $daiPayment);
            $_reimbursementCount   = [];
            $_reimbursement        = db('reimbursement')->where(['order_id' => $orderId])->select();
            $zhuReimbursementMoney = 0;
            $daiReimbursementMoney = 0;
            $zhuReimbursement      = ['title' => '报销请款审核', 'state' => 1, 'reason' => '', 'code' => 0];
            $daiReimbursement      = ['title' => '主材请款审核', 'state' => 1, 'reason' => '', 'code' => 0];
            foreach ($_reimbursement as $i) {
                if (($i['classification'] == 1 || $i['classification'] == 2 || $i['classification'] == 3 || $i['classification'] == 7) && $i['status'] == 0) {
                    //建渣打拆
                    $zhuReimbursementMoney += $i['money'];
                }
                if ($i['classification'] == 4 && $i['status'] == 0) {//运费
                    $daiReimbursementMoney += $i['money'];
                }
            }
            if ($zhuReimbursementMoney > 0) {
                $zhuReimbursement['state']  = 0;
                $zhuReimbursement['reason'] = '你有费用报销未通过';
                $zhuReimbursement['code']   = 5;
                
            }
            if ($daiReimbursementMoney > 0) {
                $daiReimbursement['state']  = 0;
                $daiReimbursement['reason'] = '你有主材请款未通过';
                $daiReimbursement['code']   = 8;
            }
            array_push($list['zhu'], $zhuReimbursement);
            array_push($list['dai'], $daiReimbursement);
            $sysConfig        = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
            $sysConfig        = explode(',', $sysConfig);
            $materialUsagess  = db('material_usage')->where(['status' => 0, 'order_id' => $orderId])->select();
            $zhuMaterialusage = ['title' => '主合同材料领用', 'state' => 1, 'reason' => '', 'code' => 0];
            $daiMaterialusage = ['title' => '代购材料领用', 'state' => 1, 'reason' => '', 'code' => 0];
            foreach ($materialUsagess as $l) {
                if (!in_array($l['invclasscode'], $sysConfig)) {
                    $zhuMaterialusage['state']  = 0;
                    $zhuMaterialusage['reason'] = '你有材料未通过';
                    $zhuMaterialusage['code']   = 6;
                }
                if (in_array($l['invclasscode'], $sysConfig)) {
                    $daiMaterialusage['state']  = 0;
                    $daiMaterialusage['reason'] = '你有材料未通过';
                    $daiMaterialusage['code']   = 6;
                }
            }
            array_push($list['zhu'], $zhuMaterialusage);
            array_push($list['dai'], $daiMaterialusage);
            $work_check_id    = db('work_check')->where(['work_check.type' => 1, 'order_id' => $orderId,'work_check.work_title_id' => 5])->where('delete_time', 0)->find();
            $inspection_type=Db::connect(config('database.zong'))->table('order_completion')->where(['order_id'=>$orderId,'inspection_type'=>3])->find();
            $zhuCompletion = ['title' => '用户验收单', 'state' => 1, 'reason' => '', 'code' => 0];
            $daiCompletion = ['title' => '用户验收单', 'state' => 1, 'reason' => '', 'code' => 0];
            if(empty($inspection_type)){
            $zhuCompletion = ['title' => '用户验收单', 'state' => 0, 'reason' => '用户还没有完成验收单确认，请尽快联系用户确认，用户验收是结算的必要条件', 'code' => 9];
            $daiCompletion = ['title' => '用户验收单', 'state' => 0, 'reason' => '用户还没有完成验收单确认，请尽快联系用户确认，用户验收是结算的必要条件', 'code' => 9];
                array_push($list['zhu'], $zhuCompletion);
                array_push($list['dai'], $daiCompletion);
            }else{
              Db::connect(config('database.zong'))->table('order_completion')->where(['order_id'=>$orderId,'inspection_type'=>3])->update(['work_check_id'=>$work_check_id['id']]);  
            }
            if ($data['type'] == 2) {
                if ($re['settlement_time'] != 0 || !empty($re['settlement_time']) || ((empty($capitalList[0]['agency']) || $capitalList[0]['agency'] == 0) && $daiReimbursementMoney == 0 && $daiMaterialusage['state'] == 0)) {
                    unset($list['dai']);
                }
                if ($re['cleared_time'] != 0 || !empty($re['cleared_time']) || ((empty($capitalList[0]['man']) || $capitalList[0]['man'] == 0) && $zhuReimbursementMoney == 0 && $zhuMaterialusage['state'] == 0)) {
                    unset($list['zhu']);
                }
            }
        }
        
        
        r_date($list, 200);
    }
    
    /*
    *结算标记
    */
    public function SettlementMark(RedisPackage $redis) {
        $date  = Authority::param(['order_id','type']);
        $antiDuplication='jiesuan';
        $expire=10;
        $order_id=$date['order_id'];
        //1主合同结算2代沟合同结算
        $type=$date['type'];
        // 设置缓存 设置缓存过期时间
        $tt=$redis->get(md5($order_id.$antiDuplication));
        if ($tt) {
            r_date(null, 300, "请勿重复提交");
        }
        $redis->set(md5($order_id.$antiDuplication), md5($order_id.$antiDuplication),$expire);
        $sysConfig       = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->where('statusss', 1)->value('valuess');
        $money           = (new OrderModel())->SingleSettlement($order_id);
        $material_usagess      = db('material_usage')->where(['order_id' => $order_id])->whereIn('invclasscode', $sysConfig)->field('sum(if(material_usage.status=1 and material_usage.adopt > 1648742400,material_usage.total_profit,0)) as materialUsageList,sum(if(material_usage.status=0,1,0)) as materialUsagessCount')->select();
        $material_usageList    = empty($material_usagess[0]['materialUsageList'])?0:$material_usagess[0]['materialUsageList'];
        $material_usagessCount = empty($material_usagess[0]['materialUsagessCount'])?0:$material_usagess[0]['materialUsagessCount'];
        $work_check_id    = db('work_check')->where(['work_check.type' => 1, 'order_id' => $order_id,'work_check.work_title_id' => 5])->where('delete_time', 0)->find();
        $inspection_type=Db::connect(config('database.zong'))->table('order_completion')->where(['work_check_id'=>$work_check_id['id'],'order_id'=>$order_id])->order('id desc')->find();
        if(!empty($inspection_type)){
            if($inspection_type['inspection_type'] !=3){
                r_date(null, 300, '用户还没有完成验收单确认，请尽快联系用户确认，用户验收是结算的必要条件');
            }
        }
         $app_user_previous_acceptance=\db('app_user_previous_acceptance')->join('order', 'order.order_id=app_user_previous_acceptance.order_id')->where('app_user_previous_acceptance.standard', '<>',1)->where('app_user_previous_acceptance.state', 3)->where('order.order_id', $order_id)->where('order.assignor', $this->us['user_id'])->count();
         if($app_user_previous_acceptance >0){
            r_date(null, 300, '师傅上道工序验收未审核');
         }
        if ($money['agencyMoney'] == 0 && $material_usageList != 0) {
            r_date(null, 300, '材料已领用代购主材,需增项代购主材');
        }
        $approval_record = db('approval_record', config('database.zong'))->where('order_id', $order_id)->where('status', 0)->count();
        if ($approval_record != 0) {
            r_date(null, 300, '你有订单特权及超限申请未通过');
        }
//        $main_payment  = 0;
//        $main_payment1 = 0;
//        $agent_payment = 0;
        $orderInfo           = db('order')->field('concat(p.province,c.city,y.county,order.addres) as  addres,order.cleared_time,order.settlement_time,order.channel_id,order.channel_details,order.pro_id,order.pro_id1,order.telephone,order.pro_id2,order.acceptance_time,contract.con_time,order_aggregate.main_price,order_aggregate.agent_price,order_aggregate.main_payment_price,order_aggregate.agent_payment_price,order_aggregate.agent_payment_ok_price,order_aggregate.main_payment_ok_price,order.order_agency,order_setting.fast_salary,order_setting.agent_allow,order_setting.is_prerogative,order_times.change_work_time,order_times.signing_time')
            ->join('province p', 'order.province_id=p.province_id', 'left')
            ->join('order_times', 'order_times.order_id=order.order_id', 'left')
            ->join('order_setting', 'order_setting.order_id=order.order_id', 'left')
            ->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'left')
            ->join('contract', 'order.order_id=contract.orders_id', 'left')
            ->join('city c', 'order.city_id=c.city_id', 'left')
            ->join('county y', 'order.county_id=y.county_id', 'left')
            ->where('order.order_id', $order_id)->find();
        $visa_form    = db('visa_form')->where('order_id', $order_id)->whereNUll('signing_time')->count();
        $capitalCount = db('capital')->where('ordesr_id', $order_id)->whereIn('approve', [3, 4, 5])->count();
        if ($visa_form != 0 || $capitalCount != 0) {
            r_date(null, 300, '还有正在进行的签证单没有签字，不能发起结算');
        }
        $points=db('sys_config',config('database.zong'))->where('keyss', 'points')->where('statusss', 1)->find();
        $points = json_decode($points['valuess'], true);
        Db::startTrans();
        try {
            if ($type == 1) {
                $envelopes_id          = db('envelopes')->where('type', 1)->where('ordesr_id', $order_id)->value('envelopes_id');
                $capitalList           = db('capital')->field('GROUP_CONCAT(capital_id) as capital_id,sum(if(agency=1,1,0)) as agency,sum(if(agency=0,1,0)) as man')->where('envelopes_id', $envelopes_id)->where('types', 1)->where('enable', 1)->select();
                $capital               = $capitalList[0]['capital_id'];
              
                if($orderInfo['change_work_time']<1748534400){
                $auxiliary_interactive = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $order_id)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->count();
                
                $auxiliary_interactiveCount = db('auxiliary_delivery_node')->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $order_id)->where('auxiliary_delivery_node.state', 1)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_delivery_schedule.delete_time')->column('auxiliary_delivery_node.auxiliary_delivery_schedul_id');
                if ($auxiliary_interactive > count(array_merge(array_unique($auxiliary_interactiveCount)))) {
                    throw  new  Exception('施工节点未上传，无法完工，请去工地巡检上传节点');
                }
            }else{
                 $auxiliary_interactive      = db('auxiliary_project_list')->where('auxiliary_project_list.order_id', $order_id)->where('work_process_type',1)->whereNull('auxiliary_project_list.delete_time')->whereNull('auxiliary_project_list.completion_time')->count();
                 if($auxiliary_interactive !=0){
                    throw  new  Exception('施工节点未上传，无法完工，请去工地巡检上传节点');
                 }
            }
                $work_check    = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $order_id])->field('sum(if(state=0 or state=3,1,0)) as incomplete,sum(if(state !=0 or state !=3,1,0)) as Finished')->where('delete_time', 0)->group('order_id')->select();
                $work_checkImg = Db::connect(config('database.db2'))->table('work_check')->where(['order_id' => $order_id])->where('work_title_id', 5)->where('delete_time', 0)->find();
                $order_acceptance_content  = Db::connect(config('database.zong'))->table('order_acceptance_content')->where('work_check', $work_checkImg['id'])->find();
                if (empty($work_checkImg['img']) && empty($work_checkImg['no_watermark_image'])) {
                    throw  new  Exception('完工验收没有完成，无法完工，请根据完工验收提示进行验收');
                }
                $list_process = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'list_process')->find();
                $list_process = json_decode($list_process['valuess'], true);
                if ((empty($work_check) || $work_check[0]['incomplete'] != 0 || $work_check[0]['Finished'] != count($list_process)) && empty($order_acceptance_content)) {
                    throw  new  Exception('完工验收没有完成，无法完工，请根据完工验收提示进行验收');
                }
                if (bcsub($orderInfo['main_price'], $orderInfo['main_payment_price'], 2) > 0 && bcadd($orderInfo['main_price'], $orderInfo['agent_price'], 2) > bcadd($orderInfo['main_payment_price'], $orderInfo['agent_payment_price'], 2)) {
                    throw  new  Exception('主合同收款不足，还剩' . bcsub($orderInfo['main_price'], $orderInfo['main_payment_price'], 2) . '元未收款');
                }
                if ((bcsub($orderInfo['main_price'], $orderInfo['main_payment_price'], 2) < 0 || bcsub($orderInfo['main_price'], $orderInfo['main_payment_price'], 2) > 0) && bcadd($orderInfo['main_price'], $orderInfo['agent_price'], 2) == bcadd($orderInfo['main_payment_price'], $orderInfo['agent_payment_price'], 2)) {
                    throw  new  Exception('主合同需要调账，请联系财务确认');
                }
                
                if (bcsub($orderInfo['main_payment_price'], $orderInfo['main_payment_ok_price'], 2) > 0) {
                    throw  new  Exception('主合同有审核中的收款，或要调账，请联系财务确认');
                }
                
                if (bcsub($orderInfo['main_payment_price'], $orderInfo['main_payment_ok_price'], 2) < 0 || bcsub($orderInfo['main_price'], $orderInfo['main_payment_price'], 2) < 0 || bcsub($orderInfo['main_price'], $orderInfo['main_payment_price'], 2) > 0) {
                    throw  new  Exception('主合同收款金额异常，若要调账请联系财务，若要退款请操作退款');
                }
                $aggregate      = [];
                $purchase_usage = db('purchase_usage')->where(['order_id' => $order_id])->whereNotIn('status', [1, 2])->select();
                if (!empty($purchase_usage)) {
                    throw  new  Exception('有领用到工地的材料正在审核中，如果着急，可以把订单信息告诉供应链【郭银芝】审核');
                }
                
                $routine_usage  = db('routine_usage')->where(['order_id' => $order_id])->whereNotIn('status', [1, 2])->select();
                foreach ($routine_usage as $item){
                    if ($item['secondment']==1) {
                        $secondmentUser = \db('secondment')->where('secondment.debi_id', $item['id'])->find();
                        $user=\db('user')->join('store', 'user.store_id=store.store_id', 'left')->where('user.store_id',$secondmentUser['lender_store_id'])->field('concat(store.store_name,user.username) username,reserve')->select();
                        $username='暂未配置店长';
                        if(count($user)==1){
                            $username=$user[0]['username'];
                        }else{
                            foreach ($user as $i){
                                if($i['reserve']==1){
                                    $username=$i['username'];
                                }
                            }
                        }
                        throw  new  Exception('有材料未审核，找' . $username. '店长去APP里的：我的-审批与报销-待审批的材料借调，里面审批');
                    }else{
                        throw  new  Exception('有领用到工地的材料正在审核中，如果着急，可以把订单信息告诉供应链【郭银芝】审核');
                    }
                }
                
                
                $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $order_id)->whereNull('deleted_at')->sum('personal_price');
                $orderCapital   = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $order_id)->where('status', 1)->sum('money');
                if ($personal_price < $orderCapital) {
                    throw  new  Exception('大工地结算金额加过审大工地结算金额超过清单工资');
                    
                }
                
                // if ((string)sprintf('%.2f', ($money['MainMaterialMoney'] + $money['agencyMoney'])) != (string)sprintf('%.2f', ($agent_payment + $main_payment1))) {
                //     throw  new  Exception('请联系管理员');
                // }
                
                $material_usage = db('material_usage')->where(['status' => 0, 'order_id' => $order_id])->count();
                if ($material_usage != 0) {
                    throw  new  Exception('你有材料未通过');
                }
                $reimbursement       = 0;
                $total_price         = db('material_usage')->where(['status' => 1, 'order_id' => $order_id])->where('if(adopt>=1648742400,invclasscode Not IN (' . $sysConfig . ') and adopt>1625162399,adopt>1625162399 )')->sum('total_profit');
                $_reimbursementCount = [];
                $_reimbursement      = db('reimbursement')->where(['order_id' => $order_id])->where('classification', '<>', 4)->select();
                $Break               = 0;
                $Small               = 0;
                $people              = 0;
                $freight             = 0;
                foreach ($_reimbursement as $i) {
                    if ($i['classification'] == 1 && $i['status'] == 1 && $i['adopt'] > 1625068800) {
                        //建渣打拆
                        $Break += $i['money'];
                    } elseif ($i['classification'] == 2 && $i['status'] == 1 && $i['adopt'] > 1625068800) {
                        //小材料
                        $Small += $i['money'];
                    } elseif ($i['classification'] == 3 && $i['status'] == 1 && $i['adopt'] > 1625068800) {
                        //协作人工
                        $people += $i['money'];
                    } elseif ($i['classification'] == 7 && $i['status'] == 1 && $i['adopt'] > 1625068800) {
                        //运费
                        $freight += $i['money'];
                    }
                    if ($i['status'] == 0 || $i['status'] == 3) {
                        $_reimbursementCount[] = $i;
                    }
                    $reimbursement += $i['money'];
                }
                if (count($_reimbursementCount) != 0) {
                    throw  new  Exception('你有费用报销未通过');
                }
                if ($orderInfo['main_payment_ok_price'] != 0) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '主合同销售收款结算', 'money' => round($orderInfo['main_payment_ok_price'], 2), 'orderId' => $order_id, 'type' => 15, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                $sql = "SELECT (SUM(`personal_price`)-SUM(`half_price`)) AS sum FROM app_user_order_capital AS a, (SELECT b.`user_id`, b.`order_id`,b.`capital_id`,MAX(b.created_at) AS `created_at` FROM app_user_order_capital AS b GROUP BY b.`user_id`,b.`order_id`,b.`capital_id`)AS c WHERE a.`user_id`=c.`user_id` AND a.`order_id`=c.`order_id` AND a.`capital_id`=c.`capital_id` AND a.created_at = c.created_at And a.`deleted_at` IS NULL AND a.`order_id` =" . $order_id;
                
                //减去大工地结算
                $largeReimbursement                 = db('large_reimbursement')->where(['order_id' => $order_id,'status'=>1])->sum('money');
                //减去师傅快结
                $app_user_order_capital_labor_costs = db('app_user_order_capital_labor_costs')->where(['order_id' => $order_id])->where('state', 1)->sum('personal_price');
                //师傅工资
                $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order_capital');
                $sum                = $reality_artificial->query($sql);
                if (isset($sum[0]['sum'])) {
                    $order_for_reality_artificial = round($sum[0]['sum'], 2);
                } else {
                    $order_for_reality_artificial = 0;
                }
                if ($orderInfo['fast_salary'] == 1 && $order_for_reality_artificial != 0) {
                    //减去大工地结算
                    $order_for_reality_artificial = $order_for_reality_artificial - $largeReimbursement;
                    
                } elseif ($orderInfo['fast_salary'] == 2 && (($order_for_reality_artificial != 0 && $app_user_order_capital_labor_costs != 0) || ($order_for_reality_artificial == 0 && $app_user_order_capital_labor_costs != 0))) {
                    //减去师傅快结
                    $order_for_reality_artificial = $order_for_reality_artificial - $app_user_order_capital_labor_costs;
                }
                if ($orderInfo['fast_salary'] == 2 && $app_user_order_capital_labor_costs != 0) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '师傅提成结算', 'money' => round($app_user_order_capital_labor_costs, 2), 'orderId' => $order_id, 'type' => 54, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                    
                }
                if ($order_for_reality_artificial != 0) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '师傅提成结算', 'money' => round($order_for_reality_artificial, 2), 'orderId' => $order_id, 'type' => 11, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                    
                }
                
                if (!empty($Break)) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '建渣打拆结算', 'money' => round($Break, 2), 'orderId' => $order_id, 'type' => 18, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                if (!empty($Small)) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '小材料结算', 'money' => round($Small, 2), 'orderId' => $order_id, 'type' => 19, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                if (!empty($people)) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '协作人工结算', 'money' => round($people, 2), 'orderId' => $order_id, 'type' => 17, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                if (!empty($largeReimbursement)) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '师傅提成', 'money' => round($largeReimbursement, 2), 'orderId' => $order_id, 'type' => 22, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                if (!empty($freight)) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '运费结算', 'money' => round($freight, 2), 'orderId' => $order_id, 'type' => 20, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                
                if (!empty($total_price)) {
                    array_push($aggregate, ['explanation' => '收到' . $orderInfo['addres'] . '材料成本结算', 'money' => round($total_price, 2), 'orderId' => $order_id, 'type' => 16, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                // $_main_discount_amount=db('approval_record',config('database.zong'))->where("order_id",$order_id)->where("type", 2)->where('status', 1)->where('created_time','>',$orderInfo['change_work_time'])->sum('change_value');
                $order_cleared = db('order_cleared')->where('order_id', $order_id)->where('cleared_type', 1)->find();
                $cleared_time=time();
                if ($order_cleared) {
                    throw  new  Exception('主合同结算数据重复');
                }
                if (!empty($aggregate)) {
                    foreach($aggregate as $itme){
                        $u8c_voucher_Find=Db::connect(config('database.zong'))->table('u8c_voucher')->where(['orderId' => $itme['orderId'], 'type' => $itme['type']])->where('status','<>',3)->find();
                        if(empty($u8c_voucher_Find)){
                            Db::connect(config('database.zong'))->table('u8c_voucher')->insertGetId(['explanation' => $itme['explanation'], 'money' => $itme['money'] ,'orderId' => $itme['orderId'], 'type' => $itme['type'], 'create_time' =>$itme['create_time'], 'prepareddate' => $itme['prepareddate']]);
                        }
                    }
                }
                if (is_mobile($orderInfo['telephone'])) {
                db('customers_points',config('database.zong'))->where('order_id', $order_id)->where('cleared_type', 1)->delete();
                db('customers_points',config('database.zong'))->insert(['cleared_type' => 1, 'cleared_time' =>$cleared_time, 'create_time' =>$cleared_time,  'order_id' => $order_id,'mobile'=>$orderInfo['telephone'],'obtain_type'=>1,'points'=>round($money['MainMaterialMoney']*$points['proportion'],2),'configure_days'=>$points['day'],'proportion'=> $points['proportion'],'start_time'=>$cleared_time,'expiry_time'=>$cleared_time + (86400* $points['day'])]);
                }
                OrderModel::update(['cleared_time' =>$cleared_time], ['order_id' => $order_id]);
                Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $order_id])->update(['cleared_time' => $cleared_time, 'status' => 5]);
            }
            
            if ($type == 2) {
                if (bcsub($orderInfo['agent_price'], $orderInfo['agent_payment_price'], 2) > 0 && bcadd($orderInfo['main_price'], $orderInfo['agent_price'], 2) > bcadd($orderInfo['main_payment_price'], $orderInfo['agent_payment_price'], 2)) {
                    throw  new  Exception('代购合同收款不足，还剩' . bcsub($orderInfo['agent_price'], $orderInfo['agent_payment_price'], 2) . '元未收款');
                };
                if ((bcsub($orderInfo['agent_price'], $orderInfo['agent_payment_price'], 2) < 0 || bcsub($orderInfo['agent_price'], $orderInfo['agent_payment_price'], 2) > 0) && bcadd($orderInfo['main_price'], $orderInfo['agent_price'], 2) == bcadd($orderInfo['main_payment_price'], $orderInfo['agent_payment_price'], 2)) {
                    throw  new  Exception('代购合同需要调账，请联系财务确认');
                }
                if (bcsub($orderInfo['agent_payment_price'], $orderInfo['agent_payment_ok_price'], 2) > 0) {
                    throw  new  Exception('代购合同有审核中的收款，或要调账，请联系财务确认');
                }
                if (bcsub($orderInfo['agent_payment_price'], $orderInfo['agent_payment_ok_price'], 2) < 0 || bcsub($orderInfo['agent_price'], $orderInfo['agent_payment_price'], 2) < 0 || bcsub($orderInfo['agent_price'], $orderInfo['agent_payment_price'], 2) > 0) {
                    throw  new  Exception('代购合同收款金额异常，若要调账请财务，若要退款请操作退款');
                }
                $anceList = [];
                if (!empty($orderInfo['settlement_time'])) {
                    throw  new  Exception('该订单已经结算');
                }
         
                if ($material_usagessCount != 0) {
                    throw  new  Exception('你有材料未通过');
                }
                $_reimbursement      = [];
                $reimbursementMoney1 = db('reimbursement')->where(['order_id' => $order_id])->where('classification', 4)->field('status,money,secondary_classification')->select();
                $money1 = [];
                $money2 = [];
                foreach ($reimbursementMoney1 as $list) {
                    if ($list['status'] == 1 && $list['secondary_classification'] != 15) {
                        $money1[] = $list['money'];
                    }
                    if ($list['status'] == 1 && $list['secondary_classification'] == 15) {
                        $money2[] = $list['money'];
                    }
                    
                    if ($list['status'] == 0 || $list['status'] == 3) {
                        $_reimbursement[] = $list['money'];
                    }
                }
                if ($orderInfo['agent_allow'] == 0) {
                    if (count($reimbursementMoney1) == 0 && $material_usageList == 0 && $orderInfo['is_prerogative'] == 0 && $orderInfo['order_agency'] == 1) {
                        throw  new  Exception('没有主材请款，不能结算');
                    }
                }
                
                if (count($_reimbursement) != 0) {
                    throw  new  Exception('你有费用报销未通过');
                    
                }
                if (empty($orderInfo['acceptance_time']) && $orderInfo['agent_price'] > 0) {
                    throw  new  Exception('代购验收后结算');
                }
                // if ((string)sprintf('%.2f', ($money['MainMaterialMoney'] + $money['agencyMoney'])) != (string)($agent_payment + $main_payment1)) {
                //     throw  new  Exception('请联系管理员');
                // }
                if ($orderInfo['agent_payment_ok_price'] != 0) {
                    array_push($anceList, ['explanation' => '收到' . $orderInfo['addres'] . '代购合同销售收款结算', 'money' => round($orderInfo['agent_payment_ok_price'], 2), 'orderId' => $order_id, 'type' => 14, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                    
                }
                if (array_sum($money1) != 0) {
                    array_push($anceList, ['explanation' => '收到' . $orderInfo['addres'] . '代购请款结算', 'money' => round(array_sum($money1), 2), 'orderId' => $order_id, 'type' => 12, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                if (array_sum($money2) != 0) {
                    array_push($anceList, ['explanation' => '收到' . $orderInfo['addres'] . '代购请款结算-主材安装设计费-结转代购合同成本', 'money' => round(array_sum($money2), 2), 'orderId' => $order_id, 'type' => 52, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                
                if (!empty($material_usageList)) {
                    array_push($anceList, ['explanation' => '收到' . $orderInfo['addres'] . '代购材料成本结算', 'money' => round($material_usageList, 2), 'orderId' => $order_id, 'type' => 40, 'create_time' => time() * 1000, 'prepareddate' => date('Y-m-d', time()),]);
                }
                // $_agent_discount_amount=db('approval_record',config('database.zong'))->where("order_id",$order_id)->where("type", 3)->where('status', 1)->where('created_time','>',$orderInfo['change_work_time'])->sum('change_value');
                $order_cleared = db('order_cleared')->where('order_id', $order_id)->where('cleared_type', 2)->find();
                $cleared_time=time();
                if ($order_cleared) {
                    throw  new  Exception('代购结算数据重复');
                }
                if (is_mobile($orderInfo['telephone'])) {
                    db('customers_points',config('database.zong'))->where('order_id', $order_id)->where('cleared_type', 2)->delete();
                    db('customers_points',config('database.zong'))->insert(['cleared_type' => 2, 'cleared_time' =>$cleared_time, 'create_time' =>$cleared_time,  'order_id' => $order_id,'mobile'=>$orderInfo['telephone'],'obtain_type'=>1,'points'=>round($money['agencyMoney']*$points['proportion'],2),'configure_days'=>$points['day'],'proportion'=> $points['proportion'],'start_time'=>$cleared_time,'expiry_time'=>$cleared_time + (86400* $points['day'])]);
                    }
                if (!empty($anceList)) {
                    foreach($anceList as $itme){
                        $u8c_voucher_Find=Db::connect(config('database.zong'))->table('u8c_voucher')->where(['orderId' => $itme['orderId'], 'type' => $itme['type']])->where('status','<>',3)->find();
                        if(empty($u8c_voucher_Find)){
                            Db::connect(config('database.zong'))->table('u8c_voucher')->insertGetId(['explanation' => $itme['explanation'], 'money' => $itme['money'] ,'orderId' => $itme['orderId'], 'type' => $itme['type'], 'create_time' =>$itme['create_time'], 'prepareddate' => $itme['prepareddate']]);
                        }
                    }
                }
                OrderModel::update(['settlement_time' => $cleared_time], ['order_id' => $order_id]);
                db('agency_order')->where('order_id', $order_id)->where('status', '<', 15)->where('delete_time', 0)->update(['status' => 15]);
                db('agency_order_sub')->where('order_id', $order_id)->where('delete_time', 0)->update(['status' => 7]);
                
            }
            Db::connect(config('database.zong'))->table('customers_bind_personal')->where('order_id', $order_id)->update(['expire_time' => time()]);
            if(($orderInfo['main_price'] !=0 && $orderInfo['agent_price'] !=0 && (($type==1 && !empty($orderInfo['settlement_time']))|| ($type==2 && !empty($orderInfo['cleared_time'])))) || ($orderInfo['main_price'] ==0 && $orderInfo['agent_price'] !=0 && $type==2) || ($orderInfo['main_price'] !=0 && $orderInfo['agent_price'] ==0 && $type==1)){
                $Common     = new Common();
                $orderModel = new OrderModel();
                $Common->award_config_rule($order_id, $orderModel, 3);
            }
            
            Db::commit();
            sendInitializationProcessQueue($order_id,'shopownerOrderClearedTask');
            sendOrder($order_id);
            r_date(null, 200, '成功');
        } catch (Exception $e) {
            Db::rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }

    /*
     * 师傅结算50%
     */
    public function HalfSettlement() {
        
        r_date([], 300, '已停止此功能');

//        Db::connect(config('database.db2'))->startTrans();
//        OrderModel::startTrans();
//        try {
//            OrderModel::update(['master_half_cost_time'=>time()], ['order_id'=>$data['order_id']]);
//            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id'=>$data['order_id']])->update(['master_half_cost_time'=>time()]);
//            Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $data['order_id'])->where('deleted_at', 'null')->update(['half_price'=>Db::raw('personal_price*0.5')]);
//            Db::connect(config('database.db2'))->commit();
//            OrderModel::commit();
//            r_date([], 200);
//        } catch (Exception $e) {
//            Db::connect(config('database.db2'))->rollback();
//            OrderModel::rollback();
//            r_date([], 300, $e->getMessage());
//        }
    }
    
    /*
     * 收款详情
     */
    public function NewCollection(OrderPaymentNodes $orderPaymentNodes) {
        //state等于0未到节点1完成2当前节点3超期提醒4待入帐
        $data                = Authority::param(['orderId']);
        $order_payment_nodes = $orderPaymentNodes->ListFind($data['orderId']);
        $content             = '';
        $toExamine           = 0;
        $toExaminePaymentId  = 0;
        $countContene        = '';
        $explain             = '';
        if (!empty($order_payment_nodes)) {
            $count               = $order_payment_nodes['count'];
            $order_payment_nodes = $order_payment_nodes['order_payment_nodes'];
//            $coupon_use_type     = array_column($order_payment_nodes, 'node_code');
//            array_multisort($coupon_use_type, SORT_ASC, $order_payment_nodes);
            $nodeCodeState = 0;
            if ($nodeCodeState == 0) {
                foreach ($order_payment_nodes as $k => $item) {
                    if ($item['state'] == 2 || $item['state'] == 3) {
                        $nodeCodeState                         += 1;
                        $order_payment_nodes[$k]['current']    = 1;
                        $order_payment_nodes[$k]['SubContent'] = 1;
                        break;
                    }
                }
            }
//            foreach ($order_payment_nodes as $k => $item) {
//                $order_payment_nodes[$k]['SubContent'] = 0;
//                if ($item['state'] == 2) {
//                    $nodeCodeState                         += 1;
//                    $order_payment_nodes[$k]['current']    = 1;
//                    $order_payment_nodes[$k]['SubContent'] = 1;
//                    break;
//                }
//            }
            if ($count == 3) {
                $countContene = '订单支付方式为首中尾三次付款';
            } elseif ($count == 2) {
                $countContene = '订单支付方式为首尾两次付款';
            } else {
                $countContene = '订单支付方式为一次性付款';
            }
            $channel_id = Db::connect(config('database.zong'))->table('order_info')->where('order_id', $data['orderId'])->value('channel_title');
            
            if ($channel_id == "京东" || $channel_id == "天猫" || $channel_id == "淘宝") {
                if ($order_payment_nodes[0]['payment_switch_1'] == 2) {
                    $explain = '此订单为' . $channel_id . '渠道订单，请引导客户使用' . $channel_id . '付款，感谢支持';
                }
                
            }
            $Common = Common::order_for_payment($data['orderId']);
            
            if ($Common[6] != 0) {
                $toExamine          = $Common[6];
                $toExaminePaymentId = $Common[7];
                $content            = '客户有新的付款，需要您审核，请及时审核';
            }
        }
        $Visa                = new Visa();
        $order_payment_nodes = $Visa->arraySort($order_payment_nodes, 'node_pay_sort', SORT_ASC);
        r_date(['SubContent' => $order_payment_nodes, 'content' => $content, 'count' => $countContene, 'explain' => $explain, 'toExamine' => $toExamine, 'toExaminePaymentId' => $toExaminePaymentId, 'isNeedPaper' => empty($order_payment_nodes) ? 0 : $order_payment_nodes[0]['isNeedPaper']], 200, '成功');
    }
    
    /*
     * 收款审核查看
     */
    public function reviewView() {
        $payment = \db('payment')->join('order', 'order.order_id=payment.orders_id', 'left')->where('order.assignor', $this->us['user_id'])->whereNull('payment.cleared_time')->where('to_examine', 2)->field('order.addres,order.order_id')->find();
        $res     = ['content' => '', 'orderId' => 0];
        if ($payment) {
            $res = ['content' => '订单地址为：' . $payment['addres'] . '的订单，用户选择现金收款，请确认，确认后该笔收款审核才会转至财务', 'orderId' => $payment['order_id']];
        }
        r_date($res, 200, '成功');
    }
    
    /*
     * 收款确认审核
     */
    public function CollectionReview(OrderModel $orderModel, \app\api\model\Common $common) {
        $data            = Authority::param(['orderId', 'id', 'type']);
        $to_examine_time = time();
        if ($data['type'] == 1) {
            \db('payment')->where('orders_id', $data['orderId'])->where('payment_id', $data['id'])->update(['to_examine' => 1, 'to_examine_time' => $to_examine_time]);
        } else {
            \db('payment')->where('orders_id', $data['orderId'])->where('payment_id', $data['id'])->update(['success' => 3, 'reject' => '店长驳回', 'to_examine' => 3, 'to_examine_time' => $to_examine_time]);
        }
        \db('order_times')->where('order_id', $data['orderId'])->where('first_payment_time', 0)->update(['first_payment_time' => $to_examine_time]);
        $order = db('order')->where('order_id', $data['orderId'])->value('state');
        if ($order == 3 && $data['type'] == 1) {
            $paymentMoney      = db('payment')->where('payment.orders_id', $data['orderId'])->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')->sum('money');
            $node_code         = Db::connect(config('database.zong'))->table('order_payment_nodes')->where('order_id', $data['orderId'])->where('payment_id', $data['id'])->value('node_code');
            $offer             = $orderModel->TotalProfit($data['orderId']);
            $all_amount_main   = strval($offer['MainMaterialMoney']);
            $all_amount_agency = strval($offer['agencyMoney']);
            
            if ($paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.499 || (config('cityId')=='246' && $paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.35)) {
                if (bcadd($all_amount_main, $all_amount_agency, 2) >= 10000 || ($all_amount_main < 10000 && $node_code != 0) || $all_amount_main == '0.00' || (config('cityId')=='246' && $paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.35)) {
                    $order = db('order')->where('order_id', $data['orderId'])->update(['state' => 4]);
                    $common->CommissionCalculation($data['orderId'], $orderModel, 2);
                    remind($data['orderId'], 4);
                }
            }
            
        }
        r_date(null, 200, '成功');
    }
    
    /*
     * KA订单信息采集添加
     */
    public function orderCollectionAdd() {
        $data      = Authority::param(['orderId', 'list']);
        $list      = json_decode($data['list'], true);
        $listArray = [];
        foreach ($list as $l) {
            foreach ($l['select'] as $v) {
                if (isset($v['choose']) && $v['choose'] == 1) {
                    $listArray[] = ['content_id' => $l['id'], 'result_id' => $v['id'], 'order_id' => $data['orderId'], 'user_id' => $this->us['user_id'], 'type' => 1, 'creation_time' => time(),];
                }
                
            }
        }
        $sys_config  = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'order_collection')->value('valuess');
        $sys_config  = json_decode($sys_config, true);
        $listArrayId = array_unique(array_column($listArray, 'content_id'));
        if (empty($listArray) || (count($listArrayId) < count($sys_config))) {
            r_date(null, 300, '选项不能为空');
        }
        Db::connect(config('database.zong'))->table('order_collection')->where('order_id', $data['orderId'])->delete();
        Db::connect(config('database.zong'))->table('order_collection')->insertAll($listArray);
        r_date(null, 200, '成功');
    }
    
    /*
    * KA订单信息采集详情
    */
    public function orderCollectionInfo() {
        $data             = Request::instance()->get();
        $orderId          = isset($data['orderId']) ? trim($data['orderId']) : 0;
        $order_collection = [];
        if (!empty($data)) {
            $order_collection = Db::connect(config('database.zong'))->table('order_collection')->field('content_id,result_id,order_id')->where('order_id', $orderId)->select();
        }
        $sys_config = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'order_collection')->value('valuess');
        $sys_config = json_decode($sys_config, true);
        
        foreach ($sys_config as $k => $i) {
            $sys_config[$k]['required'] = 1;
            foreach ($i['select'] as $k1 => $item) {
                $sys_config[$k]['select'][$k1]['choose'] = 0;
                
                foreach ($order_collection as $v) {
                    if ($i['id'] == $v['content_id']) {
                        if ($item['id'] == $v['result_id']) {
                            $sys_config[$k]['select'][$k1]['choose'] = 1;
                        }
                    }
                    
                }
            }
        }
        r_date($sys_config, 200, '成功');
    }
  
}